Ios Swift2的阵列
我有两个独立的.swift文件。我想使用ManagePerson.swift来管理我的Ios Swift2的阵列,ios,arrays,swift2,Ios,Arrays,Swift2,我有两个独立的.swift文件。我想使用ManagePerson.swift来管理我的字符串,比如添加和检索。另一个ViewController.swift创建用于访问数据的ManagePerson类数组 以我的名义,斯威夫特 func addPerson(name: String, code: String, description: String){ self.name = name self.code = code self.description = descri
字符串
,比如添加和检索。另一个ViewController.swift创建用于访问数据的ManagePerson类数组
以我的名义,斯威夫特
func addPerson(name: String, code: String, description: String){
self.name = name
self.code = code
self.description = description
}
在我的ViewController.swift中
var personList = [PersonTable]() // Declared at class level
for jsonObjectString in resultArray! {
let name = jsonObjectString["Name"] as! String
let code = jsonObjectString["Code"] as! String
let description = jsonObjectString["Description"] as! String
self.personList[count].addPerson(Name, code: code, description: description)
count++
}
然而,我似乎无法执行
.addPerson
方法。我得到一个错误“Thread:6:EXC_BAD_指令(code=EXC_I386_INVOP,subcode=0x0)”这是因为self.personList[count]
是nil
它不包含任何PersonTable的实例。首先,让我们假设您用(a)三个属性定义了“person”类;和(b)设置这些属性的init
方法:
class Person {
let name: String
let code: String
let description: String
init(name: String, code: String, description: String) {
self.name = name
self.code = code
self.description = description
}
}
然后,要实例化一个人
,只需
let person = Person(name: "Joe Montana", code: "16", description: "Quarterback")
如果需要这些Person
对象的数组,可以将其定义为:
var personList = [Person]()
因此,要向该数组添加Person
,它是:
personList.append(Person(name: "Joe Montana", code: "16", description: "Quarterback"))
因此,如果resultArray
是一个字典数组,您可以添加如下项:
for dictionary in resultArray! {
let name = dictionary["Name"] as! String
let code = dictionary["Code"] as! String
let description = dictionary["Description"] as! String
personList.append(Person(name: name, code: code, description: description))
}
但是,请注意,我们不必处理count
(您只需添加到数组中即可)
或者,如果这些值可以是nil
,您可以将它们定义为可选值:
class Person {
let name: String?
let code: String?
let description: String?
init(name: String?, code: String?, description: String?) {
self.name = name
self.code = code
self.description = description
}
}
及
for dictionary in resultArray! {
let name = dictionary["Name"] as? String
let code = dictionary["Code"] as? String
let description = dictionary["Description"] as? String
personList.append(Person(name: name, code: code, description: description))
}