Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate an array with index in Swift 3

Tags:

arrays

swift

I'm trying to iterate an array with an index in Swift 3 but keep getting

Expression type '[Int]' is ambiguous without more context

this is reproducible with the following example in a playground:

var a = [Int]()
a.append(1)
a.append(2)
// Gives above error
for (index, value) in a {
  print("\(index): \(value)")
}

I'm not sure what context it is asking for.

like image 448
Friedrich 'Fred' Clausen Avatar asked Nov 01 '16 01:11

Friedrich 'Fred' Clausen


2 Answers

You forgot to call a.enumerated(), which is what gives you the (index, value) tuples. for value in a is what gives you each element without the index.

like image 158
NRitH Avatar answered Oct 12 '22 01:10

NRitH


Correct Code:

var a = [Int]()
a.append(1)
a.append(2)
// Gives above error
for (index, value) in a.enumerated() {
    print("\(index): \(value)")
}
like image 24
2 revs, 2 users 94% Avatar answered Oct 12 '22 01:10

2 revs, 2 users 94%