How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in order to shuffle the deck.
相关问题
- How to get the maximum of more than 2 numbers in V
- “Zero out” sensitive String data in Swift
- Faster loop: foreach vs some (performance of jsper
- Convert Array to custom object list c#
- pick a random item from a javascript array
相关文章
- Numpy matrix of coordinates
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- PHP: Can an array have an array as a key in a key-
- How can I vertically align my status bar item text
- Accessing an array element when returning from a f
Swift 3 solution, following @Nate Cook answer: (work if the index starts with 0, see comments below)
You can use generic
swap
function as well and implement mentioned Fisher-Yates:or less verbose:
In Swift 4.2, there is now a method for both a mutable
shuffle
and immutableshuffled
. You can read more about the random generation and array stuff here.In Swift 2.0, GameplayKit may come to the rescue! (supported by iOS9 or later)
This is what I use:
Swift 4 Shuffle the elements of an array in a for loop where i is the mixing ratio
Or with extension Int