I am currently creating an iOS app based on the math card game "Set", and I am running into a problem simplifying the switch case statement. My goal is to avoid an ugly series of nested switches in my view. I come from a background of OOP and normally I would store references to an object and call them later where I want; however, I am trying to be functional. Below is a some code describing roughly what I would like to do.
struct CardView: View {
var card: SetGame<CardShape, CardShading, CardColor>.Card
var cardShape: some Shape {
switch card.shape {
case .diamond:
return Diamond()
case .squiggle:
return Squiggle()
case .oval:
return Oval()
}
}
var cardShading: some ViewModifier {
switch card.shading {
case .open:
return .stroke()
case .striped:
return .stripe()
case .solid:
return .fill()
}
}
var cardColor: Color
{
switch card.color {
case .red:
return Color.red
case .green:
return Color.green
case .purple:
return Color.purple
}
}
var body: some View {
VStack {
ForEach(0..<card.count) { _ in
cardShape.cardShading
}
.aspectRatio(contentAspectRatio, contentMode: .fit)
}
.foregroundColor(cardColor)
.padding()
.cardify(selected: card.selected)
}
// MARK: Drawing Constants
let contentAspectRatio: CGSize = CGSize(width: 2, height: 1)
}
Now the above code does not work for obvious reasons, it is more about conveying what I am trying to accomplish. The easy brute force solution I see would be to have three nested switch/case statements, but I have to believe there is another way. I tried using type erasure in card shape doing something like this...
var cardShape: some View {
switch card.shape {
case .diamond:
return AnyView(Diamond())
case .squiggle:
return AnyView(Squiggle())
case .oval:
return AnyView(Oval())
}
}
and while this does "work", it is no longer a shape and I lose access to my shape modifiers (ie. fill, stripe, stroke). I am pretty sure I won't be able to store my ViewModifiers and call them at a different place, so I am sort of expecting there to be one switch/case inside of my var body. If someone has a completely different approach or if I am just doing something stupid, feel free to let me know! I am trying to learn the most "Swiftish" way of doing things. Thanks in advance!