从数组中随机选取一个元素 [英] Pick a random element from an array

查看:55
本文介绍了从数组中随机选取一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组,我想随机选择一个元素.

Suppose I have an array and I want to pick one element at random.

最简单的方法是什么?

显而易见的方法是array[random index].但也许有类似 ruby​​ 的 array.sample 的东西?或者如果不能,可以通过使用扩展来创建这样的方法吗?

The obvious way would be array[random index]. But perhaps there is something like ruby's array.sample? Or if not could such a method be created by using an extension?

推荐答案

Swift 4.2 及更高版本

推荐的新方法是 Collection 协议的内置方法:randomElement().它返回一个可选项以避免我之前假设的空情况.

The new recommended approach is a built-in method on the Collection protocol: randomElement(). It returns an optional to avoid the empty case I assumed against previously.

let array = ["Frodo", "Sam", "Wise", "Gamgee"]
print(array.randomElement()!) // Using ! knowing I have array.count > 0

如果您不创建数组并且不能保证计数 > 0,您应该执行以下操作:

If you don't create the array and aren't guaranteed count > 0, you should do something like:

if let randomElement = array.randomElement() { 
    print(randomElement)
}

Swift 4.1 及以下

只是回答你的问题,你可以这样做来实现随机数组选择:

Just to answer your question, you can do this to achieve random array selection:

let array = ["Frodo", "sam", "wise", "gamgee"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

铸件很难看,但我相信它们是必需的,除非其他人有其他方法.

The castings are ugly, but I believe they're required unless someone else has another way.

这篇关于从数组中随机选取一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆