9

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.

3
  • Saying in a gives you one value (i.e. 1, or 2), not a tuple with both an index and a value. Commented Nov 1, 2016 at 1:27
  • Can anyone help me understand why this question received a downvote? How can I improve it? Commented Nov 1, 2016 at 1:29
  • 1
    It's so careless. for (index,value) in a, when a is an array, is just silly talk. Commented Nov 1, 2016 at 1:30

2 Answers 2

26

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Correct Code:

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

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.