将Variable添加到我的数组中

时间:2017-02-11 11:23:07

标签: arrays swift

struct Section {
    var name: String!
    var items: [String]!
    var collapsed: Bool!

    init(name: String, items: [String], collapsed: Bool = false) {
        self.name = name
        self.items = items
        self.collapsed = collapsed
    }
}

这是我的结构,我有下面的变量

var array1 : Section = Section(name:"",items:[])

如何为array1添加新名称?我不想附加我需要的内容如下

sections = [
            Section(name: "Mac", items: ["MacBook", "MacBook Air", "MacBook Pro", "iMac", "Mac Pro", "Mac mini", "Accessories", "OS X El Capitan"]),
            Section(name: "iPad", items: ["iPad Pro", "iPad Air 2", "iPad mini 4", "Accessories"]),
            Section(name: "iPhone", items: ["iPhone 6s", "iPhone 6", "iPhone SE", "Accessories"]),
        ]

2 个答案:

答案 0 :(得分:0)

如果我找对你,你可以这样取代名字:

var array1 : Section = Section(name:"",items:[])
array1.name = "New Name"
print(array1)  //Section(name: New Name, items: [], collapsed: false)

修改

var array1 : Section = Section(name:"",items:[])

array1.name.append("New FamilyName")    //"New FamilyName"
array1.name                             //"New FamilyName"

正如您所看到的,array1.name为空,您已追加"New FamilyName"。结果它会给你"New FamilyName"

但如果array1.name

中有价值
var array1 : Section = Section(name:"New Name",items:[])

array1.name.append("New FamilyName")    //"New NameNew FamilyName"
array1.name                             //"New NameNew FamilyName"

这会将新字符串附加到现有字符串中。

现在如果你完全替换而不使用追加

var array1 : Section = Section(name:"New Name",items:[])

array1.name                           //"New Name"
array1.name = "Complete New Value"    //replace original value 
array1.name                           //"Complete New Value"  
print(array1)                         //"Section(name: Complete New Value, items: [], collapsed: false)\n"

答案 1 :(得分:0)

你需要的是array1本身是一个Sections数组:

var array1: [Section] = []

array1.append(Section(name: "Mac", items: ["MacBook", "MacBook Air", "MacBook Pro", "iMac", "Mac Pro", "Mac mini", "Accessories", "OS X El Capitan"]))

array1.append(Section(name: "iPad", items: ["iPad Pro", "iPad Air 2", "iPad mini 4", "Accessories"]))

array1.append(Section(name: "iPhone", items: ["iPhone 6s", "iPhone 6", "iPhone SE", "Accessories"]))