如何使用arc4random_uniform从数组中随机选择一个值

giw*_*ook 2 swift

我有一个带有一些值的数组,我想从随机中选择一个值,但是我在执行时遇到了一些麻烦.我是Swift的新手,所以我不确定我在这里做错了什么.

let types = ["value1", "value2", "value3"]

class someClass {
    let type = String(arc4random_uniform(UInt32(types)))
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,我收到错误 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]
}
Run Code Online (Sandbox Code Playgroud)

但后来我得到了这个错误: Playground execution failed: <EXPR>:39:22: error: 'BlogPost.Type' does not have a member named 'x' let type = types[x] ^

到目前为止,我一直只和Swift工作了一个月,所以如果你们能分享我对我尝试过的两种方法的见解,我肯定会感激,如果两种方法都可以解决,你们如何重新编写这两个例子的代码使它工作?

das*_*ght 5

以下是如何做到这一点:

let types = ["value1", "value2", "value3"]
let type = types[Int(arc4random_uniform(UInt32(types.count)))]
println(type)
Run Code Online (Sandbox Code Playgroud)
  • 的演员阵容countUInt32是必要的,因为arc4random_uniform需要一个无符号值
  • 的演员arc4random_uniform来背Int,因为数组下标操作者需要[]接受一个Int.

演示(单击底部的[编译]以运行).