简体   繁体   English

使用arc4random使用Swift获取数组中的随机元素

[英]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. 表达式解析为未使用的l值。

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. Playground允许您执行此操作,因为它是用于玩代码的。 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)))])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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