我正在尝试加载一个包含结构数据的简单数组。
我读过不使用元组所以我使用结构。
以下是在 Playground 上写的;但数组仍然为零。
我做错了什么?
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]? 只是一个声明,所以之后数组仍然是 nil。在 myPeople?.append(john) 中使用了可选链接,并且仅当 myPeople 不为 nil 时才执行 append。尝试
var myPeople:[person]? = []
myPeople?.append(john)
或
var myPeople:[person] = []
myPeople.append(john)
