How do I shuffle an array in Swift?

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

    This is a version of Nate's implementation of the Fisher-Yates shuffle for Swift 4 (Xcode 9).

    extension MutableCollection {
        /// Shuffle the elements of `self` in-place.
        mutating func shuffle() {
            for i in indices.dropLast() {
                let diff = distance(from: i, to: endIndex)
                let j = index(i, offsetBy: numericCast(arc4random_uniform(numericCast(diff))))
                swapAt(i, j)
            }
        }
    }
    
    extension Collection {
        /// Return a copy of `self` with its elements shuffled
        func shuffled() -> [Element] {
            var list = Array(self)
            list.shuffle()
            return list
        }
    }
    

    The changes are:

    • The constraint Indices.Iterator.Element == Index is now part of the Collection protocol, and need not be imposed on the extension anymore.
    • Exchanging elements must done by calling swapAt() on the collection, compare SE-0173 Add MutableCollection.swapAt(_:_:).
    • Element is an alias for Iterator.Element.

提交回复
热议问题