I have two seperate .swift files. And I want to use ManagePerson.swift to manage my Strings
such as adding and retrieving. The other ViewController.swift creates an array of ManagePerson class for accessing the data.
In my ManagePerson.swift
func addPerson(name: String, code: String, description: String){
self.name = name
self.code = code
self.description = description
}
In my 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++
}
However, I can't seem to perform .addPerson
method. I get an error of "Thread: 6: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"
First, let's imagine you defined your "person" class with (a) three properties; and (b) an init
method to set these properties:
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
}
}
Then, to instantiate a Person
, it's just
let person = Person(name: "Joe Montana", code: "16", description: "Quarterback")
If you want an array of these Person
objects, you define it as:
var personList = [Person]()
And thus, to add a Person
to this array, it is:
personList.append(Person(name: "Joe Montana", code: "16", description: "Quarterback"))
So, if resultArray
is an array of dictionaries, you add items like so:
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))
}
But, note, we don't have to mess with count
(as you can just add to the array).
Or, if these values could be nil
, you'd define these as optionals:
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
}
}
and
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))
}
这是因为self.personList[count]
为nil
它不包含任何PersonTable
实例
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.