How to access a random index inside an array

I am trying to access an array using random indexes, using a arc4randomrandom index to generate. I apologize if my “technical use of terms” is incorrect, as I am fairly new to development.

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 does not give me any problems. Based on php background, I can not understand what is happening here.

Thanks! :) PS: I try this on XCODE 6 inside the Swift Playground

+5
source share
2 answers

This is due to the rapid application of type safety.

arc4random() a UInt32, Int.

, i Int, .

, Int i:

var shot = backLeft[Int(i)]

, i, i:

var i = Int(arc4random()%(3))
var shot = backLeft[i]
+10

Swift 5, , Array randomElement():

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

, indices Array Range randomElement():

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

Source: https://habr.com/ru/post/1543245/


All Articles