Swift – Randomly reorder an Array

 

This code sample demonstrates how you can reorder an array.

A possible scenario is when you have multiple-choise questions that you want to present in a different order every time they are shown.

var arrUniqueNumbers = [1,2,3,4]        
print("Array before shuffle: \(arrUniqueNumbers)")    
let count = arrUniqueNumbers.count
for i in 0..<count{
            let n = Int(arc4random_uniform(UInt32(count-i)))+i            
            (arrUniqueNumbers[i], arrUniqueNumbers[n]) = 
                              (arrUniqueNumbers[n], arrUniqueNumbers[i])
           }
print("Array after shuffle: \(arrUniqueNumbers)")

 

Leave a Reply