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 th…


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

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.


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-06-14T05:00:00+00:00) How to shuffle an array in Swift. Retrieved from https://www.scien.cx/2021/06/14/how-to-shuffle-an-array-in-swift/

MLA
" » How to shuffle an array in Swift." flaviocopes.com | Sciencx - Monday June 14, 2021, https://www.scien.cx/2021/06/14/how-to-shuffle-an-array-in-swift/
HARVARD
flaviocopes.com | Sciencx Monday June 14, 2021 » How to shuffle an array in Swift., viewed ,<https://www.scien.cx/2021/06/14/how-to-shuffle-an-array-in-swift/>
VANCOUVER
flaviocopes.com | Sciencx - » How to shuffle an array in Swift. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/14/how-to-shuffle-an-array-in-swift/
CHICAGO
" » How to shuffle an array in Swift." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/06/14/how-to-shuffle-an-array-in-swift/
IEEE
" » How to shuffle an array in Swift." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/06/14/how-to-shuffle-an-array-in-swift/. [Accessed: ]
rf:citation
» How to shuffle an array in Swift | flaviocopes.com | Sciencx | https://www.scien.cx/2021/06/14/how-to-shuffle-an-array-in-swift/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.