#37: Shuffle Arrays in Swift

Swift gives you two built-in APIs for random ordering:

let values = [1, 2, 3, 4]
let copy = values.shuffled()

shuffled() returns a new array, while shuffle() mutates the existing one:

var mutable = [1, 2, 3, 4]
mutable.shuffle()

Use the non-mutating version when you want to preserve the original order, and the mutating version when you do not.


I'm also on Twitter and GitHub.

Subscribe via RSS.