2
let index1 = arc4random_uniform(10);

let x = array[index1];

The second line is giving following error

could not find an overload for 'subscript' that accepts the supplied arguments

let x = array[index1];
        ^~~~~~~~~~~~~
2
  • Pass the int value by type casting it Commented Jun 13, 2014 at 6:38
  • Can you give an example? Commented Jun 13, 2014 at 6:41

1 Answer 1

5

you have to convert the index to Int like e.g. this:

let index1: UInt32 = arc4random_uniform(10); // with the type of the value
let x = array[Int(index1)];

the Int is the proper index type rather than UInt32.

UPDATE

if you are not quiet happy to convert the index every individual time, you can also add an extension to Array with defining a new subscript for your generic index type(s), e.g. such extension would look with UInt32 like this:

extension Array {
    subscript (index: UInt32) -> T {
        get {
            let intIndex : Int = Int(index)
            return self[intIndex]
        }
    }
}

NOTE: I have not worked out the setter here.

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

4 Comments

Thanks holex -- just started swift today and didn't know how to typecast. I was trying (Int)index1 and it obviously was not fixing it :-)
This isn't typecasting. You're initialising a new Int with the UInt32 value. It's the right answer, with a slightly misleading explanation
yes, that is true, unfortunately the pure casting like index1 as Int is just not working in that case, I re-phrased and also have extended my answer.
The type annotation for index1 is not necessary, just let index1 = arc4random_uniform(10) works as well.

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.