假设我有一个数组,我想随机选择一个元素。
最简单的方法是什么?
最明显的方法是array[random index]。但也许有一些类似ruby的array。sample?如果没有,可以通过使用扩展来创建这样的方法吗?
假设我有一个数组,我想随机选择一个元素。
最简单的方法是什么?
最明显的方法是array[random index]。但也许有一些类似ruby的array。sample?如果没有,可以通过使用扩展来创建这样的方法吗?
当前回答
Swift 4.2及以上版本
新的推荐方法是Collection协议上的内置方法:randomElement()。它返回一个可选选项,以避免前面假设的空情况。
let array = ["Frodo", "Samwise", "Merry", "Pippin"]
print(array.randomElement()!) // Using ! knowing I have array.count > 0
如果你不创建数组,也不保证计数> 0,你应该这样做:
if let randomElement = array.randomElement() {
print(randomElement)
}
Swift 4.1及以下版本
为了回答你的问题,你可以这样做来实现随机数组选择:
let array = ["Frodo", "Samwise", "Merry", "Pippin"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])
演员阵容很难看,但我相信他们是必须的,除非有人有别的办法。
其他回答
检查空数组的替代功能实现。
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])
Swift 3 -简单易用。
创建数组 var arrayOfColors = [UIColor. var红色,用户界面颜色。黄色,用户界面颜色。橙色,UIColor.green] 创建随机颜色 let randomColor = arc4random() % UInt32(arrayOfColors.count) 将该颜色设置为对象 你的项目= arrayOfColors[Int(randomColor)]
下面是SpriteKit项目用随机字符串更新SKLabelNode的一个例子:
let array = ["one","two","three","four","five"]
let randomNumber = arc4random() % UInt32(array.count)
let labelNode = SKLabelNode(text: array[Int(randomNumber)])
如果你想要获得多个随机元素从你的数组没有重复,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.
Swift的另一个建议
private extension Array {
var randomElement: Element {
let index = Int(arc4random_uniform(UInt32(count)))
return self[index]
}
}
你可以使用Swift内置的random()函数以及扩展:
extension Array {
func sample() -> Element {
let randomIndex = Int(rand()) % count
return self[randomIndex]
}
}
let array = [1, 2, 3, 4]
array.sample() // 2
array.sample() // 2
array.sample() // 3
array.sample() // 3
array.sample() // 1
array.sample() // 1
array.sample() // 3
array.sample() // 1