我想聲明一個自定義類型數組並添加幾個項目。如何聲明數組並在同一行上添加項目?
class ClassA:NSObject {
var property1: String?
var property2: String?
}
var myarray = [ClassA]()
如何將ClassA的新實例添加到與上述聲明相同的行中的數組?
我想聲明一個自定義類型數組並添加幾個項目。如何聲明數組並在同一行上添加項目?
class ClassA:NSObject {
var property1: String?
var property2: String?
}
var myarray = [ClassA]()
如何將ClassA的新實例添加到與上述聲明相同的行中的數組?
你可以添加自定義的初始化和數組,像這樣上使用類型推斷:
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"),
]
你可以這樣來做:
var classAarray: [ClassA] = []
var newClassA = ClassA()
classAarray.append(newClassA)
或者這樣說:
var classAarray: [ClassA] = [ClassA(), ClassA(), ClassA()]
已經看清楚Apple Documentation reference上做陣列多個動作
像這樣:
var myarray = [ClassA()]
或
var myarray = [ClassA](count: 10, repeatedValue: ClassA())