Swift中的struct数组

Swift中的struct数组,swift,struct,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:

单元迭代产生误差

找不到成员“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 {

首先,您不应该在struct中使用init(),因为 结构具有初始值设定项默认值。然后在此代码块中:

/*
var count: Int = 0
for count in contacts {
    println("\(contacts[count].name)") // here's where I get an error
}
*/
您的变量“count”不是整数,它的类型是“Person”。 试试这个:

/*
for count in contacts {
    println(count.name) // It`s must be OKey.
}
*/

我希望我能帮助你,并为我糟糕的英语感到抱歉:D

谢谢,安东尼奥。它实际上和我以前在Python中使用的一样。我想我把简单的东西复杂化了。还有enumerate,我忘了它在Swift中可用。
/*
var count: Int = 0
for count in contacts {
    println("\(contacts[count].name)") // here's where I get an error
}
*/
/*
for count in contacts {
    println(count.name) // It`s must be OKey.
}
*/