gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:48:20 24 4
gpt4 key购买 nike

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

以下是在 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)

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com