如何将结构加载到数组中? [英] How do you load structs into an Array?

查看:74
本文介绍了如何将结构加载到数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用结构数据加载一个简单的数组.
我读过不要使用元组,而是使用结构.

以下是在操场上写的;但是数组仍然为零.

我在做什么错了?

I'm trying to load a simple array with struct data.
I've read not to use tuples so am using structs.

The following was written in playground; but the array is still nil.

What am I doing wrong?

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]?只是一个声明,因此array在此之后仍为nil.在 myPeople?.append(john)中,使用了可选链接,并且仅当 myPeople 不为零时才执行 append .试试

var myPeople:[person]? is only a declaration, so array is still nil after that. In myPeople?.append(john) optional chaining is used and append is only executed if myPeople is not nil. Try

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

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

这篇关于如何将结构加载到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆