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

时间:2014-09-12 02:02:58

标签: swift

我有一个带有一些值的数组,我想从随机选择一个值但是我在执行时遇到了一些麻烦。我是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合作了一个月,所以如果你们能分享我对我尝试过的两种方法的见解,我肯定会感激,如果两种方法都可以修改,你们如何修改代码两个例子都能使它发挥作用吗?

1 个答案:

答案 0 :(得分:5)

以下是如何做到这一点:

let types = ["value1", "value2", "value3"]
let type = types[Int(arc4random_uniform(UInt32(types.count)))]
println(type)
  • countUInt32的演员表是必要的,因为arc4random_uniform采用无符号值
  • 由于数组下标运算符arc4random_uniform采用Int,因此需要[]强制转换为Int

Demo(点击底部的[编译]即可运行)。