How do I shuffle an array in Swift?

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

    Swift 3 solution, following @Nate Cook answer: (work if the index starts with 0, see comments below)

    extension Collection {
        /// Return a copy of `self` with its elements shuffled
        func shuffle() -> [Generator.Element] {
            var list = Array(self)
            list.shuffleInPlace()
            return list
        } }
    
    extension MutableCollection where Index == Int {
        /// Shuffle the elements of `self` in-place.
        mutating func shuffleInPlace() {
            // empty and single-element collections don't shuffle
            if count < 2 { return }
            let countInt = count as! Int
    
        for i in 0..

提交回复
热议问题