How do I shuffle an array in Swift?

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

    Working Array Extension (mutating & non-mutating)

    Swift 4.1 / Xcode 9

    The top answer is deprecated, so I took it upon myself to create my own extension to shuffle an array in the newest version of Swift, Swift 4.1 (Xcode 9):

    extension Array {
    
    // Non-mutating shuffle
        var shuffled : Array {
            let totalCount : Int = self.count
            var shuffledArray : Array = []
            var count : Int = totalCount
            var tempArray : Array = self
            for _ in 0..<totalCount {
                let randomIndex : Int = Int(arc4random_uniform(UInt32(count)))
                let randomElement : Element = tempArray.remove(at: randomIndex)
                shuffledArray.append(randomElement)
                count -= 1
            }
            return shuffledArray
        }
    
    // Mutating shuffle
        mutating func shuffle() {
            let totalCount : Int = self.count
            var shuffledArray : Array = []
            var count : Int = totalCount
            var tempArray : Array = self
            for _ in 0..<totalCount {
                let randomIndex : Int = Int(arc4random_uniform(UInt32(count)))
                let randomElement : Element = tempArray.remove(at: randomIndex)
                shuffledArray.append(randomElement)
                count -= 1
            }
            self = shuffledArray
        }
    }
    

    Call Non-Mutating Shuffle [Array] -> [Array]:

    let array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    
    print(array.shuffled)
    

    This prints array in a random order.


    Call Mutating Shuffle [Array] = [Array]:

    var array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    
    array.shuffle() 
    // The array has now been mutated and contains all of its initial 
    // values, but in a randomized shuffled order
    
    print(array) 
    

    This prints array in its current order, which has already been randomly shuffled.


    Hopes this works for everybody, if you have any questions, suggestions, or comments, feel free to ask!

    0 讨论(0)
提交回复
热议问题