user3839756
user3839756

Reputation: 813

Iterating through an array of Tuples

Im trying to iterate through an array of Tuples using an Index.

Heres my Array:

var keyValueArray = [(name: "One", value: 1), (name: "Four", value: 4), (name: "Two", value: 2) ]

Heres what I want to do:

func tupleArrayInsertionSort(var unsortedTupleArray: [(String,Int)]){
var key, y : Int
for i in 0..<unsortedTupleArray.count {
    key = unsortedTupleArray.[i]
}

}

However I get the error: Cannot subscript a value of type [(String,Int)]

I am just wanting to iterate through the Tuples not into them. How can I accomplish this?

Upvotes: 3

Views: 4526

Answers (1)

Lance
Lance

Reputation: 9012

The problem is with this line:

key = unsortedTupleArray.[i]

You have a . between the array and the subscript. It should look like this:

key = unsortedTupleArray[i]

but that only gets you the tuple, if you want to pull out the Int, you need to access the second element in the tuple

key = unsortedTupleArray[i].1

Now, if you want to preserve the names of the tuples, you should keep them in the function declaration. Then you can access the value using .value:

var keyValueArray = [(name: "One", value: 1), (name: "Four", value: 4), (name: "Two", value: 2) ]

func tupleArrayInsertionSort(var unsortedTupleArray: [(name: String, value: Int)]){
    var key, y : Int
    for i in 0..<unsortedTupleArray.count {
        key = unsortedTupleArray[i].value
    }
}

Upvotes: 4

Related Questions