Array of structure in Swift

Iteration of elements causes an error

could not find element 'convertFromStringInterpolationSegment'

println("\(contacts[count].name)")" , while the 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 where I get an error } println(contacts[0].name) // prints just fine - "Jack" 
+6
source share
2 answers

The for-in loop iterates over a set of elements and provides the actual element, not its index at each iteration. Thus, your loop should be rewritten as:

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

Note that this line:

 var count: Int = 0 

does not affect your code, because the count variable in the for-in overridden and visible to the code block nested inside the loop.

If you still want to play with indexes, you need to change your loop like:

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

or

 for count in 0..<contacts.count { 

Finally, if you need both an index and a value, perhaps the easiest way is to use the global enumerate function, which returns a list (index, value) of tuples:

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

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

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

the variable "count" is not an integer, its type is "Person". Try the following:

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

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

0
source

Source: https://habr.com/ru/post/982436/


All Articles