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.
Apart from these two you can also use custom shuffle method. If you prefer to implement your own shuffling algorithm, you can do so by using Swift’s standard library functions like swapAt()
and randomElement()
. This approach provides more control over the shuffling process.
var array = [1, 2, 3, 4, 5] for i in 0..<(array.count - 1) { let j = Int.random(in: i..<(array.count)) array.swapAt(i, j) }
This code snippet demonstrates a custom shuffle algorithm. It iterates through the array and swaps elements randomly.
Shuffling with GameplayKit
Swift developers can also take advantage of the GameplayKit framework, which offers a more sophisticated way to shuffle arrays. This framework provides a GKRandomSource
class that allows you to control the randomness of shuffling.
import GameplayKit var array = [1, 2, 3, 4, 5] array = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: array) as! [Int]
By following these examples, you can practice array shuffling in Swift and incorporate it into your projects.
In conclusion, shuffling an array in Swift is a useful skill for many iOS and macOS app development scenarios. Whether you opt for the built-in shuffled()
method, a custom algorithm, or leverage the GameplayKit framework, you now have the knowledge to shuffle arrays effectively.
So, go ahead and make your apps more dynamic by adding the power of array shuffling to your programming arsenal!