How do I shuffle an array in Swift?

前端 未结 25 2269
长发绾君心
长发绾君心 2020-11-21 05:44

How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in o

25条回答
  •  面向向阳花
    2020-11-21 06:27

    This is what I use:

    import GameplayKit
    
    extension Collection {
        func shuffled() -> [Iterator.Element] {
            let shuffledArray = (self as? NSArray)?.shuffled()
            let outputArray = shuffledArray as? [Iterator.Element]
            return outputArray ?? []
        }
        mutating func shuffle() {
            if let selfShuffled = self.shuffled() as? Self {
                self = selfShuffled
            }
        }
    }
    
    // Usage example:
    
    var numbers = [1,2,3,4,5]
    numbers.shuffle()
    
    print(numbers) // output example: [2, 3, 5, 4, 1]
    
    print([10, "hi", 9.0].shuffled()) // output example: [hi, 10, 9]
    

提交回复
热议问题