Hello world,
I'm building a cards came using SwiftUI and for now I have created the cards, but I want to shuffle them, so mix them randomly. Can anyone please tell me the syntax to do it? Thanks very much.
Shuffle randomly in SwiftUI
You have a deck of 52 cards, in an array I suppose ?
Just use shuffle() on it.
Here is a toy example:
var cards = [1, 2, 3, 4, 5, 6]
cards.shuffle()
print(cards)
- First draw: [4, 6, 3, 1, 2, 5]
- Second draw: [6, 1, 3, 4, 2, 5]
Okay, but the problem is where to locate them. I did something like this, but it gives errors.
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
var cards = [1, 2, 3, 4, 5, 6]
var body: some View {
cards.shuffle()
print(cards)
}
}
PlaygroundPage.current.setLiveView(ContentView())