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"
Copy Behaviour: As Swift's Array is a structure type. This means that the array is copied when they are assigned to other variables or constant or passed to a function.
Swift said "yes," which means that types like Array and Dictionary and String are structs rather than classes. They get copied on assignment, and on passing them as parameters.
We can use the map(_:) method to transform the elements of the array. I would like to create an array that contains the number of characters of each string in the array. We invoke map(_:) on strings and pass a closure to the map(_:)
Struct Inheritance in Swift: Not Possible! However, one thing that classes do and structs don't is inheritance. An example of when you cannot use a struct is when you need inheritance. To create a parent-class-child-class hierarchy in your code, use a class instead of a struct.
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)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With