如何将结构加载到数组中?

时间:2014-11-08 19:47:53

标签: arrays swift struct

我试图加载一个包含struct数据的简单数组。
我读过不使用元组所以使用结构。

以下是在操场上写的;但阵列仍然是零。

我做错了什么?

struct person {
    var firstName:String?
    var lastName:String?
    init(firstName:String, lastName:String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

let john = person(firstName: "John", lastName: "Doe")
let rich = person(firstName: "Richard", lastName: "Brauer")
let ric = person(firstName: "Ric", lastName: "Lee")
let Merrideth = person(firstName: "Merrideth", lastName: "Lind")

var myPeople:[person]?

myPeople?.append(john)
myPeople?.append(rich)
myPeople?.append(ric)
myPeople?.append(Merrideth)

println(myPeople)

2 个答案:

答案 0 :(得分:3)

var myPeople:[person]?只是一个声明,所以数组在此之后仍为零。在myPeople?.append(john)中使用了可选链接,append仅在myPeople不为零时执行。尝试

var myPeople:[person]? = [] 
myPeople?.append(john)

var myPeople:[person] = [] 
myPeople.append(john)

答案 1 :(得分:0)

我认为这里不需要选项,因为你以一种需要定义变量的方式进行初始化。因此,我将删除您的选项,并向您展示如何逐个地将结构附加到数组中,并自动执行。

以下是如何将结构附加到数组ONE BY ONE:

struct person {
    var firstName : String
    var lastName : String
    init ( firstName : String, lastName : String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

let john = person(firstName: "John", lastName: "Doe")
let rich = person(firstName: "Richard", lastName: "Brauer")
let ric = person(firstName: "Ric", lastName: "Lee")
let Merrideth = person(firstName: "Merrideth", lastName: "Lind")

var myPeople = [person]

myPeople.append(john)
myPeople.append(rich)
myPeople.append(ric)
myPeople.append(Merrideth)

println(myPeople)

以下是在创建结构实例时自动将结构附加到数组的方法:

struct person {
    var firstName : String
    var lastName : String
    init ( firstName : String, lastName : String) {
        self.firstName = firstName
        self.lastName = lastName
        myPeople.append(self)
    }
}
var myPeople = [person]

let john = person(firstName: "John", lastName: "Doe")
let rich = person(firstName: "Richard", lastName: "Brauer")
let ric = person(firstName: "Ric", lastName: "Lee")
let Merrideth = person(firstName: "Merrideth", lastName: "Lind")

println(myPeople)

希望这有帮助!