[英]how to pick a random ten (String) from an array in swift
could anyone teach me how to select an item ( String
) from an array by using arc4random_uniform()
? 谁能教我如何使用
arc4random_uniform()
从数组中选择一个项目( String
arc4random_uniform()
? I tried but I couldn't because arc4random_uniform
can be used for selecting Int. 我试过了,但不能,因为
arc4random_uniform
可用于选择Int。
Swift 3 Extension Swift 3扩展
While Oisdk answer works, a extension could be more useful instead of writing that coding over and over again. 尽管Oisdk答案有效,但扩展可能会比重复编写该代码更有用。
import Foundation
extension Array {
func randomElement() -> Element {
if isEmpty { return nil }
return self[Int(arc4random_uniform(UInt32(self.count)))]
}
}
let myArray = ["dog","cat","bird"]
myArray.randomElement() //dog
myArray.randomElement() //dog
myArray.randomElement() //cat
myArray.randomElement() //bird
Subscripting an array takes and Int, but arc4random_uniform returns a UInt32. 用数组下标需要Int,但是arc4random_uniform返回UInt32。 So you just need to convert between those types.
因此,您只需要在这些类型之间进行转换。
import Foundation
let array = ["ab", "cd", "ef", "gh"]
let randomItem = array[Int(arc4random_uniform(UInt32(array.count)))]
Also, arc4random_uniform gives a random number less that its argument. 同样,arc4random_uniform给出的随机数要比其参数少。 So just cast array.count to a UInt32, and it'll work.
因此,只需将array.count强制转换为UInt32即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.