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
Taking Nate's algorithm I wanted to see how this would look with Swift 2 and protocol extensions.
This is what I came up with.
Now, any
MutableCollectionType
can use these methods given it usesInt
as anIndex
With Swift 3, if you want to shuffle an array in place or get a new shuffled array from an array,
AnyIterator
can help you. The idea is to create an array of indices from your array, to shuffle those indices with anAnyIterator
instance andswap(_:_:)
function and to map each element of thisAnyIterator
instance with the array's corresponding element.The following Playground code shows how it works:
You can refactor the previous code and create a
shuffled()
function inside anArray
extension in order to get a new shuffled array from an array:Usage:
As an alternative to the previous code, you can create a
shuffle()
function inside anArray
extension in order to shuffle an array in place:Usage:
Form the article of Fisher–Yates shuffle on Wikipedia
Swift 3.1,4.0
a). Pencil-and-paper method :
b). Modern method:(Durstenfeld's version)
Extension:
a). Pencil-and-paper method :
b). Modern method:(Durstenfeld's version)
Reference :
Note: You can use empty array also.
Output:
Please let me know if any queries, Other Swift version will be check soon.
Here's something possibly a little shorter:
This is how its done in a Simplest way.
import Gamplaykit
to your VC and use the below code. Tested in Xcode 8.If you want to get a shuffled String from an Array you can use below code..