我有一个包含一些值的数组,我想从其中随机选择一个值,但执行时遇到一些问题。我是 Swift 新手,所以我不确定我在这里做错了什么。
let types = ["value1", "value2", "value3"]
class someClass {
let type = String(arc4random_uniform(UInt32(types)))
}
使用此代码,我收到错误 Playground execution failed: <EXPR>:39:16: error: cannot invoke 'init' with an argument of type 'UInt32'
let type = String(arc4random_uniform(UInt32(types)))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我尝试了一些不同的方法,看看是否可以解决此错误。
let types = ["value1", "value2", "value3"]
class someClass {
let x = arc4random_uniform(UInt32(4))
let type = types[x]
}
但随后我收到此错误:Playground execution failed: <EXPR>:39:22: error: 'BlogPost.Type' does not have a member named 'x'
let type = types[x]
^
到目前为止,我只使用 Swift 一个月,所以如果你们能分享你们对我尝试过的两种方法的见解,以及如果这两种方法都是可纠正的,你们将如何重新编写代码,我绝对不胜感激这两个例子都能让它工作吗?
最佳答案
以下是具体操作方法:
let types = ["value1", "value2", "value3"]
let type = types[Int(arc4random_uniform(UInt32(types.count)))]
println(type)
- 将
count
转换为UInt32
是必要的,因为arc4random_uniform
采用无符号值 - 需要将
arc4random_uniform
转换回Int
,因为数组下标运算符[]
采用Int
。
Demo (点击底部【编译】即可运行)。
关于swift - 如何使用 arc4random_uniform 从数组中随机选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25799634/