在Swift中从数组中获取随机元素

我有一个像这样的数组:

var names: String = [ "Peter", "Steve", "Max", "Sandra", "Roman", "Julia" ]

我想从该数组中获取3个随机元素。我来自C#,但是我不确定该从哪里开始。我想我应该先对数组进行随机排序,然后再从中选择前3个项目?

我尝试使用以下扩展名将其改组:

extension Array

{

mutating func shuffle()

{

for _ in 0..<10

{

sort { (_,_) in arc4random() < arc4random() }

}

}

}

但随后在“ shuffle()”的位置说“’()’不可转换为’[Int]’”。

为了挑选一些元素,我使用:

var randomPicks = names[0..<4];

到目前为止看起来还不错。

如何洗牌?还是有人对此有更好/更优雅的解决方案?

回答:

extension Collection {

func choose(_ n: Int) -> ArraySlice<Element> { shuffled().prefix(n) }

}

游乐场测试

var alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

let shuffledAlphabet = alphabet.shuffled() // "O", "X", "L", "D", "N", "K", "R", "E", "S", "Z", "I", "T", "H", "C", "U", "B", "W", "M", "Q", "Y", "V", "A", "G", "P", "F", "J"]

let letter = alphabet.randomElement() // "D"

var numbers = Array(0...9)

let shuffledNumbers = numbers.shuffled()

shuffledNumbers // [8, 9, 3, 6, 0, 1, 4, 2, 5, 7]

numbers // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

numbers.shuffle() // mutate it [6, 0, 2, 3, 9, 1, 5, 7, 4, 8]

numbers // [6, 0, 2, 3, 9, 1, 5, 7, 4, 8]

let pick3numbers = numbers.choose(3) // [8, 9, 2]


extension RangeReplaceableCollection {

/// Returns a new Collection shuffled

var shuffled: Self { .init(shuffled()) }

/// Shuffles this Collection in place

@discardableResult

mutating func shuffledInPlace() -> Self {

self = shuffled

return self

}

func choose(_ n: Int) -> SubSequence { shuffled.prefix(n) }

}


var alphabetString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

let shuffledAlphabetString = alphabetString.shuffled // "DRGXNSJLFQHPUZTBKVMYAWEICO"

let character = alphabetString.randomElement() // "K"

alphabetString.shuffledInPlace() // mutate it "WYQVBLGZKPFUJTHOXERADMCINS"

alphabetString // "WYQVBLGZKPFUJTHOXERADMCINS"

let pick3Characters = alphabetString.choose(3) // "VYA"

以上是 在Swift中从数组中获取随机元素 的全部内容, 来源链接: utcz.com/qa/429894.html

回到顶部