How do I shuffle an array in Swift?

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

    In SWIFT 4

    func createShuffledSequenceOfNumbers(max:UInt)->[UInt] {
    
        var array:[UInt]! = []
        var myArray:[UInt]! = []
        for i in 1...max {
            myArray.append(i)
        }
        for i in 1...max {
            array.append(i)
        }
        var tempArray:[Int]! = []
        for index in 0...(myArray.count - 1) {
    
            var isNotFinded:Bool = true
            while(isNotFinded){
    
                let randomNumber = arc4random_uniform(UInt32(myArray.count))
                let randomIndex = Int(randomNumber)
    
                if(!tempArray.contains(randomIndex)){
                    tempArray.append(randomIndex)
    
                    array[randomIndex] = myArray[index]
                    isNotFinded = false
                }
            }
        }
    
        return array
    }
    

提交回复
热议问题