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

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

问题描述

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

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

最简单的方法是什么?

最明显的方法是array[random index].但是也许有红宝石的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

如果不创建数组并且不能保证count> 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天全站免登陆