swift - Swift 中的结构数组

标签 swift struct

元素迭代产生错误

could not find member '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"

最佳答案

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

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

注意这一行:

var count: Int = 0

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

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

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)")
}

关于swift - Swift 中的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28500278/

相关文章:

ios - Swift 3 照片拍摄

ios - NSArray 元素无法匹配 Swift 数组元素类型预期 NSMutableArray 但发现 __NSDictionaryI :

swift - 如何从 UICollectionView 中选择多个图像并将它们传输到另一个 View Controller?

ios - 检查数组是否具有相同的纬度经度 swift

c - "struct inside struct"中的限制

c++ - std::map<struct,struct>::find 没有找到匹配项,但是如果我通过 begin() 循环到 end() 我会在那里看到匹配项

ios - 将 NSDictionary 中的特定元素添加到 NSArray

c - 存储大小未知

无法访问结构成员

c - 写入通过结构传递给线程的 mmap 输出 (C)