How do I shuffle an array in Swift?

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

    In my case, I had some problems of swapping objects in Array. Then I scratched my head and went for reinventing the wheel.

    // swift 3.0 ready
    extension Array {
    
        func shuffled() -> [Element] {
            var results = [Element]()
            var indexes = (0 ..< count).map { $0 }
            while indexes.count > 0 {
                let indexOfIndexes = Int(arc4random_uniform(UInt32(indexes.count)))
                let index = indexes[indexOfIndexes]
                results.append(self[index])
                indexes.remove(at: indexOfIndexes)
            }
            return results
        }
    
    }
    

提交回复
热议问题