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
This is how to shuffle one array with a seed in Swift 3.0.
This is what I use:
Edit: As noted in other answers, Swift 4.2 finally adds random number generation to the standard library, complete with array shuffling.
However, the
GKRandom
/GKRandomDistribution
suite in GameplayKit can still be useful with the newRandomNumberGenerator
protocol — if you add extensions to the GameplayKit RNGs to conform to the new standard library protocol, you can easily get:...and still make use of the nice new "native" random APIs in Swift.
The rest of this answer concerns such RNGs and/or their use in older Swift compilers.
There are some good answers here already, as well as some good illustrations of why writing your own shuffle can be error-prone if you're not careful.
In iOS 9, macOS 10.11, and tvOS 9 (or later), you don't have to write your own. There's an efficient, correct implementation of Fisher-Yates in GameplayKit (which, despite the name, is not just for games).
If you just want a unique shuffle:
If you want to be able to replicate a shuffle or series of shuffles, choose and seed a specific random source; e.g.
In iOS 10 / macOS 10.12 / tvOS 10, there's also a convenience syntax for shuffling via an extension on
NSArray
. Of course, that's a little cumbersome when you're using a SwiftArray
(and it loses its element type on coming back to Swift):But it's pretty easy to make a type-preserving Swift wrapper for it:
Working Array Extension (mutating & non-mutating)
Swift 4.1 / Xcode 9
The top answer is deprecated, so I took it upon myself to create my own extension to shuffle an array in the newest version of Swift, Swift 4.1 (Xcode 9):
Call Non-Mutating Shuffle
[Array] -> [Array]
:This prints
array
in a random order.Call Mutating Shuffle
[Array] = [Array]
:This prints
array
in its current order, which has already been randomly shuffled.Hopes this works for everybody, if you have any questions, suggestions, or comments, feel free to ask!
In SWIFT 4
It stop at "swap(&self[i], &self[j])" when I upgrade the xCode version to 7.4 beta.
fatal error: swapping a location with itself is not supported
So I add a condition as below
YA! It's OK for me.