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

标签 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 一个月,所以如果你们能分享你们对我尝试过的两种方法的见解,以及如果这两种方法都是可纠正的,你们将如何重新编写代码,我绝对不胜感激这两个例子都能让它工作吗?

最佳答案

以下是具体操作方法:

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/

相关文章:

objective-c - 需要 SpriteKit 碰撞仅在第一次接触时发生

ios - 如何覆盖和继承 Swift 中的扩展?

generics - Swift:在函数失败时向下转换为通用类型

ios - 在处理容器 VC 时无法让我的委托(delegate)协议(protocol)工作?

ios - 为什么最后调用 DataTaskWithRequest?

swift - 字体 'SF Mono' 的 NSFont 名称是什么?

swift - 我想在我的 View 上画一条细线,如我链接的图像所示

ios - Swift 1 代码可以在 iOS 9 上运行吗?

ios - 按下按钮到下一个 "storyboard"在 Swift 中以编程方式设计 UI

ios - UIWebView 与 Django