AI Workshop: learn to build apps with AI →
Collections: Shuffling Arrays

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


This tutorial belongs to the Swift series

Suppose you have an array in Swift, like this:

var items = [1, 2, 3]

and you want to shuffle it so that you get its items in random order.

There are 2 ways to do that in Swift.

One way is to mutate the original array using the shuffle() method, which shuffles the items in place:

items.shuffle()

Note that I used var because an array is a struct, and if I declare it as let then it’s immutable, and you will get an error.

Another way is to leave the original array unchanged and get a new array using the shuffled() method:

let items = [1, 2, 3]
let shuffledItems = items.shuffled()

Note that here you can safely use let to declare your variables because shuffled() does not mutate the original array.

Lessons in this unit:

0: Introduction
1: Arrays
2: ▶︎ Shuffling Arrays
3: Random Array Items
4: Dictionaries
5: Sets
6: Tuples