5

I'm trying to access an array using random indexes by using arc4random to generate the random index. I'm sorry if my "technical usage of terms" are incorrect as I am fairly new to the development scene.

var backLeft = ["Clear","Drop","Smash"];    
var i = (arc4random()%(3))
var shot = backLeft[i]

This gives me an error on the third line,

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

But, if I use,

var i = 2
var shot = backLeft[i]

Then it doesn't give me any issues. Coming from a php background, I can't seem to have any clue what's going wrong here.

Thank You! :) PS: I'm trying this on XCODE 6 inside the Swift Playground

2
  • Possible duplicate of Pick a random element from an array Commented Jun 9, 2016 at 18:06
  • @Dschee, I think this question was posted before array.randomElement() was a thing? Commented Jun 19, 2018 at 0:27

2 Answers 2

10

That's due to Swift's enforcement of type safety.

arc4random() returns a UInt32, and the subscript operator takes an Int.

You need to make sure i is of type Int before passing it into the subscript operator.

You can do so by initializing an Int from i:

var shot = backLeft[Int(i)]

Or, you can do the same to the random value before assigning it to i and then access i normally:

var i = Int(arc4random()%(3))
var shot = backLeft[i]
Sign up to request clarification or add additional context in comments.

1 Comment

You can also cast the array length to Uint32 rather than hard coding it: arc4random() % UInt32(backLeft.count)
1

With Swift 5, if you want to get a random element from an array, you can use Array's randomElement() method:

let array = ["Clear","Drop","Smash"]
let randomElement = array.randomElement()
print(String(describing: randomElement)) // Optional("Smash")

If you want to get a random index from an array, you can use Array's indices property and Range's randomElement() method:

let array = ["Clear","Drop","Smash"]
let randomIndex = array.indices.randomElement()
print(String(describing: randomIndex)) // Optional(1)

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.