Reputation: 95
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)"
Upvotes: 0
Views: 80
Reputation: 438222
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))
}
Upvotes: 2
Reputation: 999
It is because self.personList[count]
is nil
it doesn't contain any instance of PersonTable
Upvotes: 0