JL64 JL64 -4 years ago 157
Swift Question

Xcode Swift add a value to a defined array in swift

What I'm looking to try to do is have another var attached to the array to store values in without having to make a 2D array.

var list: NSMutableArray! = NSMutableArray()
list.add("Apple")
list[0].color = red // Something like this


Any help in the right direction will be appreciated

Answer Source

For that make array of custom class or struct.

struct Fruit {
    let name: String
    let color: String
}

Now make array of this struct and add object of this struct in it.

var fruits = [Fruit]()
fruits.append(Fruit(name: "Apple", color: "red"))

Now you can access object in a way you describe in your question.

print(fruits[0].name)  //Apple
print(fruits[0].color) //red

Note: In Swift use swift's type Array and Dictionary instead of NSArray and NSDictionary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download