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
works!!. organisms is the array to shuffle.
Simple Example:
Here's some code that runs in playground. You won't need to import Darwin in an actual Xcode project.
This answer details how to shuffle with a fast and uniform algorithm (Fisher-Yates) in Swift 4.2+ and how to add the same feature in the various previous versions of Swift. The naming and behavior for each Swift version matches the mutating and nonmutating sorting methods for that version.
Swift 4.2+
shuffle
andshuffled
are native starting Swift 4.2. Example usage:Swift 4.0 and 4.1
These extensions add a
shuffle()
method to any mutable collection (arrays and unsafe mutable buffers) and ashuffled()
method to any sequence:Same usage as in Swift 4.2 examples above.
Swift 3
These extensions add a
shuffle()
method to any mutable collection and ashuffled()
method to any sequence:Same usage as in Swift 4.2 examples above.
Swift 2
(obsolete language: you can't use Swift 2.x to publish on iTunes Connect starting July 2018)
Usage:
Swift 1.2
(obsolete language: you can't use Swift 1.x to publish on iTunes Connect starting July 2018)
shuffle
as a mutating array methodThis extension will let you shuffle a mutable
Array
instance in place:shuffled
as a non-mutating array methodThis extension will let you retrieve a shuffled copy of an
Array
instance:In my case, I had some problems of swapping objects in Array. Then I scratched my head and go for reinventing the wheel.
This is a version of Nate's implementation of the Fisher-Yates shuffle for Swift 4 (Xcode 9).
The changes are:
Indices.Iterator.Element == Index
is now part of theCollection
protocol, and need not be imposed on the extension anymore.swapAt()
on the collection, compare SE-0173 AddMutableCollection.swapAt(_:_:)
.Element
is an alias forIterator.Element
.