Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of struct in Swift

Tags:

struct

swift

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"
like image 276
thinkswift Avatar asked Feb 13 '15 13:02

thinkswift


People also ask

Is array a struct in Swift?

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.

Is array struct or class Swift?

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.

How do I map an array in Swift?

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(_:)

Can struct be inherited Swift?

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.


1 Answers

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)")
}
like image 77
Antonio Avatar answered Sep 29 '22 00:09

Antonio