假设我有一个数组,我想随机选择一个元素。
最简单的方法是什么?
最明显的方法是array[random index]。但也许有一些类似ruby的array。sample?如果没有,可以通过使用扩展来创建这样的方法吗?
假设我有一个数组,我想随机选择一个元素。
最简单的方法是什么?
最明显的方法是array[random index]。但也许有一些类似ruby的array。sample?如果没有,可以通过使用扩展来创建这样的方法吗?
当前回答
检查空数组的替代功能实现。
func randomArrayItem<T>(array: [T]) -> T? {
if array.isEmpty { return nil }
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
return array[randomIndex]
}
randomArrayItem([1,2,3])
其他回答
如果你想要获得多个随机元素从你的数组没有重复,GameplayKit有你覆盖:
import GameplayKit
let array = ["one", "two", "three", "four"]
let shuffled = GKMersenneTwisterRandomSource.sharedRandom().arrayByShufflingObjects(in: array)
let firstRandom = shuffled[0]
let secondRandom = shuffled[1]
你有两个选择的随机性,见GKRandomSource:
The GKARC4RandomSource class uses an algorithm similar to that employed in arc4random family of C functions. (However, instances of this class are independent from calls to the arc4random functions.) The GKLinearCongruentialRandomSource class uses an algorithm that is faster, but less random, than the GKARC4RandomSource class. (Specifically, the low bits of generated numbers repeat more often than the high bits.) Use this source when performance is more important than robust unpredictability. The GKMersenneTwisterRandomSource class uses an algorithm that is slower, but more random, than the GKARC4RandomSource class. Use this source when it’s important that your use of random numbers not show repeating patterns and performance is of less concern.
我发现使用GameKit的gkrandomsource . sharerandom()最适合我。
import GameKit
let array = ["random1", "random2", "random3"]
func getRandomIndex() -> Int {
let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(array.count)
return randomNumber
或者可以返回所选随机下标处的对象。确保函数首先返回String,然后返回数组的索引。
return array[randomNumber]
言简意赅。
Swift 4版本:
extension Collection where Index == Int {
/**
Picks a random element of the collection.
- returns: A random element of the collection.
*/
func randomElement() -> Iterator.Element? {
return isEmpty ? nil : self[Int(arc4random_uniform(UInt32(endIndex)))]
}
}
斯威夫特3
进口GameKit
func getRandomMessage() -> String {
let messages = ["one", "two", "three"]
let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: messages.count)
return messages[randomNumber].description
}
跟随其他人的回答,但有Swift 2支持。
快1.倍
extension Array {
func sample() -> T {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
快2.倍
extension Array {
func sample() -> Element {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
例如:
let arr = [2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31]
let randomSample = arr.sample()