Swift中的struct数组

时间:2015-02-13 13:05:09

标签: swift struct

元素的迭代产生错误

  

无法找到成员'convertFromStringInterpolationSegment'

println("\(contacts[count].name)")",直接列表项打印正常。

我错过了什么?

struct Person {
    var name: String
    var surname: String
    var phone: String
    var isCustomer: Bool

    init(name: String, surname: String, phone: String, isCustomer: Bool)
    {
        self.name = name
        self.surname = surname
        self.phone = phone
        self.isCustomer = isCustomer
    }

}

var contacts: [Person] = []

var person1: Person = Person(name: "Jack", surname: "Johnson", phone: "7827493", isCustomer: false)

contacts.append(person1)

var count: Int = 0
for count in contacts {
    println("\(contacts[count].name)") // here's where I get an error
}

println(contacts[0].name) // prints just fine - "Jack"

2 个答案:

答案 0 :(得分:6)

for-in循环遍历项集合,并在每次迭代时提供实际项而不是其索引。所以你的循环应该重写为:

for contact in contacts {
    println("\(contact.name)") // here's where I get an error
}

注意这一行:

var count: Int = 0

对您的代码没有影响,因为count中的for-in变量已重新定义,并且对嵌套在循环内的代码块可见。

如果您仍想使用索引,则必须将循环修改为:

for var count = 0; count < contacts.count; ++count {

for count in 0..<contacts.count {

最后,如果你需要索引和值,也许最简单的方法是通过enumerate全局函数,它返回一个(索引,值)元组列表:

for (index, contact) in enumerate(contacts) {
    println("Index: \(index)")
    println("Value: \(contact)")
}

答案 1 :(得分:0)

首先,你不应该在struct中使用init(),因为 结构有初始化程序默认值。然后在这段代码中:

label {
  display: inline-block;
  border: 1px solid grey;
  margin-top: 8px;
  margin-left: 8px;
  width: 434px;
}

你的变量&#34;计数&#34;不是整数,它的类型是&#34; Person&#34;。 试试这个:

<label>Some text</label>
<label>Some text</label>

我希望我帮助你,抱歉我的英语不好:D

相关问题