4thSpace
4thSpace

Reputation: 44312

How to declare array and add items on same line?

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

Answers (3)

Dániel Nagy
Dániel Nagy

Reputation: 12015

Like this:

 var myarray = [ClassA()]

or

var myarray = [ClassA](count: 10, repeatedValue: ClassA())

Upvotes: 1

BoilingLime
BoilingLime

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

József Vesza
József Vesza

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

Related Questions