Skip to content

How to shuffle an array in Swift

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:

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 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.

→ Download my free Swift Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about swift: