← flaviocopes.com

How to shuffle an array in Swift

Published Jun 14 2021

Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! ✨

This tutorial belongs to the Swift series

Suppose you have an array in Swift, like this:

var items = 1...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 mutating the original array, and it’s using the shuffle() method that shuffles the items in the array:


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 not mutating the original array, but it’s returning a new array, and it’s using the shuffled() method:

let items = 1...3
let shuffledItems = items.shuffled()

Note that here I am safe to use let to declare my variables because shuffled() does not mutate the original array.

I write books for developers 👇🏼

© 2023 Flavio Copes Flavio Copes made in Italy 🇮🇹 using Notion to Site Notion to Site