How do I shuffle an array in Swift?

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

    Taking Nate's algorithm I wanted to see how this would look with Swift 2 and protocol extensions.

    This is what I came up with.

    extension MutableCollectionType where Self.Index == Int {
        mutating func shuffleInPlace() {
            let c = self.count
            for i in 0..<(c - 1) {
                let j = Int(arc4random_uniform(UInt32(c - i))) + i
                swap(&self[i], &self[j])
            }
        }
    }
    
    extension MutableCollectionType where Self.Index == Int {
        func shuffle() -> Self {
            var r = self
            let c = self.count
            for i in 0..<(c - 1) {
                let j = Int(arc4random_uniform(UInt32(c - i))) + i
                swap(&r[i], &r[j])
            }
            return r
        }
    }
    

    Now, any MutableCollectionType can use these methods given it uses Int as an Index

提交回复
热议问题