Reputation: 44312
I'd like to declare a custom typed array and add several items.
class ClassA:NSObject {
var property1: String?
var property2: String?
}
var myarray = [ClassA]()
How do I add new instances of ClassA to the array on the same line as the above declaration?
Upvotes: 0
Views: 59
Reputation: 12015
Like this:
var myarray = [ClassA()]
or
var myarray = [ClassA](count: 10, repeatedValue: ClassA())
Upvotes: 1
Reputation: 2267
You can do it this way :
var classAarray: [ClassA] = []
var newClassA = ClassA()
classAarray.append(newClassA)
Or this way :
var classAarray: [ClassA] = [ClassA(), ClassA(), ClassA()]
Have look at Apple Documentation reference to do more actions on Array
Upvotes: 0
Reputation: 4795
You could add a custom initializer and use type inference on the array like so:
class ClassA: NSObject {
var property1: String?
var property2: String?
init(property1: String, property2: String) {
super.init()
self.property1 = property1
self.property2 = property2
}
}
// ...
var myarray = [
ClassA(property1: "A1", property2: "B1"),
ClassA(property1: "A2", property2: "B2"),
ClassA(property1: "A3", property2: "B3"),
ClassA(property1: "A4", property2: "B4"),
]
Upvotes: 2