How do I shuffle an array in Swift?

前端 未结 25 2243
长发绾君心
长发绾君心 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:30

    Simple Example:

    extension Array {
        mutating func shuffled() {
            for _ in self {
                // generate random indexes that will be swapped
                var (a, b) = (Int(arc4random_uniform(UInt32(self.count - 1))), Int(arc4random_uniform(UInt32(self.count - 1))))
                if a == b { // if the same indexes are generated swap the first and last
                    a = 0
                    b = self.count - 1
                }
                swap(&self[a], &self[b])
            }
        }
    }
    
    var array = [1,2,3,4,5,6,7,8,9,10]
    array.shuffled()
    print(array) // [9, 8, 3, 5, 7, 6, 4, 2, 1, 10]
    

提交回复
热议问题