简体   繁体   中英

Using arc4random to get a random element in an array using Swift

What am I doing wrong? When I run this code in the playground I get the random element that is supposed to appear in the array, however there's an issue when I insert this code into my workspace project I get this error:

Expression resolves to an unused l-value.

var My-Array = ["Apple","Banana","Carrot","dewberry "]

My-Array[Int(arc4random_uniform(UInt32(My-Array.count)))]

This error tells you that the value that you get from your array is left unused. Playground lets you do it, because it is meant for playing with code. In production code, however, dereferencing an array and leaving the resultant value unused is a certain sign of an error.

To fix this problem, assign the value to a variable or a constant, or consume it in some other way (eg print it out):

let randomFruit = My-Array[Int(arc4random_uniform(UInt32(My-Array.count)))]

or

println(My-Array[Int(arc4random_uniform(UInt32(My-Array.count)))])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM