Shuffle an array in Swift

Swift now comes with built in shuffle functionality. Swift provides two methods

  • shuffle()
  • shuffled()

shuffle()

Shuffle reorders a collection in place. After calling shuffle on the collection the original collection is changed/reordered

var a = ["a","b","c","d","e","f"]
a.shuffle()
print(a.description)

Since shuffle() is mutating in nature you cannot use it with constant declared using let keyword. It has a complexity of O(n), where n is the length of the collection.

shuffled()

As the name suggests shuffled() returns a reordered copy leaving the original collection un touched. It can even be used on constant declared with let keyword.

let a = ["a","b","c","d","e","f"]
print(a.shuffled().description)

shuffled() has a complexity of O(n), where n is the length of the sequence.

Comment if you want to make a card game.

A pat on the back !!

NEED A JOB? NEED TO HIRE? NEED HELP?

Join group of Software Professionals

iOS DEVELOPER’S DEN