【问题标题】:How do you load structs into an Array?如何将结构加载到数组中?
【发布时间】:2015-01-05 10:21:18
【问题描述】:

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

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

我做错了什么?

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)

【问题讨论】:

  • 请注意,您不需要将数组声明为可选,除非您有充分的理由。数组在实例化后立即填充,因此很可能永远不会为零。

标签: arrays swift struct


【解决方案1】:

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

这里是如何将你的结构一个接一个地附加到数组中:

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)

希望这有帮助!

【讨论】:

  • 我在 var myPeople = [person] 处遇到错误,因为它有一个 init。我必须在末尾添加 ()。
【解决方案2】:

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

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

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

【讨论】:

  • 这是否适用于扩展 Codable 协议的结构??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 2021-04-27
  • 2012-11-09
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多