How do I shuffle an array in Swift?

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

    works!!. organisms is the array to shuffle.

    extension Array
    {
        /** Randomizes the order of an array's elements. */
        mutating func shuffle()
        {
            for _ in 0..<10
            {
                sort { (_,_) in arc4random() < arc4random() }
            }
        }
    }
    
    var organisms = [
        "ant",  "bacteria", "cougar",
        "dog",  "elephant", "firefly",
        "goat", "hedgehog", "iguana"]
    
    print("Original: \(organisms)")
    
    organisms.shuffle()
    
    print("Shuffled: \(organisms)")
    

提交回复
热议问题