7

Iteration of elements yield error

could not find member 'convertFromStringInterpolationSegment'

println("\(contacts[count].name)")", while direct list item prints fine.

What am I missing?

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 Answers 2

6

The for-in loop iterates over a collection of items, and provides the actual item and not its index at each iteration. So your loop should be rewritten as:

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

Note that this line:

var count: Int = 0

has no effect in your code, because the count variable in the for-in is redefined and visible to the block of code nested inside the loop.

If you still want to play with indexes, then you have to modify your loop as:

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

or

for count in 0..<contacts.count {

Last, if you need both the index and the value, maybe the easiest way is through the enumerate global function, which returns a list of (index, value) tuples:

for (index, contact) in enumerate(contacts) {
    println("Index: \(index)")
    println("Value: \(contact)")
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Antonio. It's actually the same as I used to have it in Python. I guess I was overcomplexing the simple. And kudos for enumerate, I forgot it's available in Swift.
0

First of all, you should not using init() in struct, because The structure has initializer default.Then in this block of code:

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

your variable "count" is not integer, it`s type is "Person". Try this:

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

I hope I help you, and sorry for my bad English:D

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.