我正试图用结构数据加载一个简单的数组。
我读过不要使用元组,所以我使用结构。
下面是在操场上写的,但数组仍然是零。
我做错什么了?

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)

最佳答案

var myPeople:[person]?只是一个声明,因此之后数组仍然为零。在myPeople?.append(john)中使用可选链接,并且只有当append不是nil时才执行myPeople。尝试

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


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

关于arrays - 如何将结构加载到数组中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26821347/

10-10 04:09