0

I want to enumerate my array of Any objects, with access to index of element. However, swift throw an error:

Type '() -> EnumeratedSequence<[Any]>' does not conform to protocol 'Sequence'`

My code is:

var arrValues : [Any]!

for (index, ob) in arrValues.enumerated() {
    print("\(index): '\(ob)'")
}

How to fix that?

0

3 Answers 3

1

You need to follow correct syntax, I thought you are doing like below image,

enter image description here

But, the actual code is,

for (index, ob) in arrValues.enumerated(){
//.....
}

Also, you need a Optional var for check it has value or not.

    var arrValues : [Any]?

    if arrValues?.count != nil{
        for (index, ob) in (arrValues?.enumerated())! {

            print("\(index): '\(ob)'")
        }
    }else{
        print("Array is Empty")
    }

Output:

Click here to see output.

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

Comments

1

This is the way you go

    var arrValues = [Any]()
    for var i in 0..<arrValues.count {

        print("\(i): '\(arrValues[i])'")
    }

This will also work

var arrValues = [Any]()
for (index, ob) in arrValues.enumerated() {
    print("\(index): '\(ob)'")
}

2 Comments

Note the difference that you have defined arrValues as implicitly unwrapped optional. Please accept the answer if it works for you.
You don't need to create the range 0 ..< arrValues.count manually. You can just use the indices property of your collection: for i in arrValues.indices. Also, why are you manually incrementing i? Swift will do that automatically.
1

Looks like you are declaring an array without creating its instance.

You can use below snippet:

var arrValues = [Any]()

for (index, ob) in arrValues.enumerated() {
    print("\(index): '\(ob)'")
}

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.