How do I shuffle an array in Swift?

前端 未结 25 2189
长发绾君心
长发绾君心 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 how its done in a Simplest way.import Gamplaykit to your VC and use the below code. Tested in Xcode 8.

     import GameplayKit
    
     let array: NSArray = ["Jock", "Ellie", "Sue Ellen", "Bobby", "JR", "Pamela"]
    
     override func viewDidLoad() {
        super.viewDidLoad()
    
        print(array.shuffled())  
    }
    

    If you want to get a shuffled String from an Array you can use below code..

    func suffleString() {
    
        let ShuffleArray = array.shuffled()
    
        suffleString.text = ShuffleArray.first as? String
    
        print(suffleString.text!)
    
    }
    

提交回复
热议问题