0

I can't figure out if this is even possible in Swift, but using a for index loop I'm trying to match the index of my array with a property located within a structure within myarray

Data:

class MyClass {

struct myStruct {
    var name: String? = ""
    var age: Double = 0
}

let myArray: [myStruct] = [
    myStruct(name: "Gary", age: 35),
    myStruct(name: "Carol", age: 60),
    myStruct(name: "Lou", age: 55)
    ]
}

Controller:

var instanceofMyClass = MyClass()

for (index, age) in enumerate(instanceofMyClass.myArray) {
    println("my index is \(index) and age is \(age)")

When I substitute my array of structs with a simple array of strings, I return a value, but cannot return a value when it's an array of structs

1 Answer 1

3

Even though your loop variables are named (index, age), you're still iterating through myArray, and that contains instances of the struct you've defined. As a result age actually contains instances of that struct instead of doubles.

You need something like this to get the age values in a loop:

for (index, myStruct) in enumerate(instanceofMyClass.myArray) {
    println("my index is \(index) and age is \(myStruct.age)")
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.