Swift 5.x iOS 13.x
I have an array of dice views I created and I want to switch between them. I just show two views here to keep this short. I created an array of the views but I can't quite figure out how to address it in SwiftUI? or indeed what sort of object a view is since it isn't a view or some view it seems.
import SwiftUI
import GameplayKit
let dotSize:CGFloat = 24
let diceSize:CGFloat = 128
let fieldSide:CGFloat = 32
let d6 = GKRandomDistribution.d2()
var diceViews:[Any] = [oneDotDice(),twoDotDice()]
struct ContentView: View {
@State var showInt:Int = 1
var body: some View {
VStack {
if showInt == 1 {
oneDotDice()
.transition(AnyTransition.opacity)
.animation(.default)
.modifier(changeDice(showInt: self.$showInt))
}
if showInt == 2 {
twoDotDice()
.transition(AnyTransition.opacity)
.animation(.default)
.modifier(changeDice(showInt: self.$showInt))
}
}
}
struct oneDotDice: View {
var body: some View {
Rectangle()
.fill(Color.clear)
.frame(width: diceSize, height: diceSize, alignment: .center)
.border(Color.black)
.background(Text(1))
}
}
struct twoDotDice: View {
var body: some View {
Rectangle()
.fill(Color.clear)
.frame(width: diceSize, height: diceSize, alignment: .center)
.border(Color.black)
.background(Text(2))
}
}
struct changeDice: ViewModifier {
@Binding var showInt:Int
func body(content: Content) -> some View {
content
.onTapGesture {
self.showInt = d6.nextInt()
print("Int ",self.showInt)
}
}
}
How can make this code better using my array of views the in main loop? I cannot even use a switch statement it seems in SwiftUI code. I need to use half a dozen nested if/else statements...