Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a random index inside an array

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

like image 746
user3083988 Avatar asked Jun 04 '14 16:06

user3083988


People also ask

How do you access an array index?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you select a random position in an array?

Code for Picking a Random Array Value The code for picking a random value from an array looks as follows: let randomValue = myArray[Math. floor(Math. random() * myArray.


1 Answers

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]
like image 127
Cezar Avatar answered Oct 20 '22 08:10

Cezar