I have a model and I have a deck variable . Now I want to remove twelve items from deck array . However the model is changing for every item I removed , I want the view to change only after twelve cards are removed.function getTwelveCards is getting run continuously and all the cards are removed. The required functionality is to remove only twelve cards Here is my model :
struct SetGame<Color, Shape, Shadings> {
var deck : Array<SetCard>
var addedTwelveCards = false
func printCardCount() {
print("card count: \(deck.count)")
}
mutating func getASetCard() -> SetCard {
deck.remove(at: 0)
}
mutating func getTwelveCards() -> Array<SetGame<Color, Shape, Shadings>.SetCard> {
var cards : Array<SetGame<Color, Shape, Shadings>.SetCard> = []
if deck.count >= 12 && !addedTwelveCards{
for _ in 1...12 {
cards.append(getASetCard())
}
}
addedTwelveCards = true
return cards
}
struct SetCard : Identifiable {
var color : Color
var shapeName : ShapeName
var shading : Shadings
var count : Int
var id = UUID()
}
}
Here is my ViewModel :
class SetGameViewModel: ObservableObject {
@Published private var setGameModel = SetGame<Color, ShapeName, Shadings>(deck: createSetGameDeck())
static let colors = [Color.red, Color.green, Color.blue]
static let shapes = [ShapeName.Capsule, ShapeName.Circle, ShapeName.Square]
static let shadings = [Shadings.fill, Shadings.striped, Shadings.stroked]
static func createSetGameDeck() -> Array<SetGame<Color, ShapeName, Shadings>.SetCard> {
var deck : Array<SetGame<Color, ShapeName, Shadings>.SetCard> = []
for color in colors {
for shape in shapes {
for shading in shadings {
for count in 1...3 {
let setCard = SetGame<Color, ShapeName, Shadings>.SetCard(color: color, shapeName: shape, shading: shading, count: count)
deck.append(setCard)
}
}
}
}
deck.shuffle()
print("\(deck.count)")
return deck
}
// MARK: Intents
func getCardCount() {
setGameModel.printCardCount()
}
var deck : Array<SetGame<Color, ShapeName, Shadings>.SetCard> {
get {
setGameModel.deck
}
}
var addedTwelveCards : Bool {
self.setGameModel.addedTwelveCards
}
var getFirstTwelveSetCards : Array<SetGame<Color, ShapeName, Shadings>.SetCard> {
print("new deck count: \(self.setGameModel.deck.count)")
return self.setGameModel.getTwelveCards()
}
}
Here is my View:
struct SetGameView: View {
@ObservedObject var setGameViewModel : SetGameViewModel
var body: some View {
Group {
if !setGameViewModel.addedTwelveCards {
Grid(self.setGameViewModel.getFirstTwelveSetCards) { setCard in
SetCardView(shapeName: setCard.shapeName, shading: setCard.shading, color: setCard.color, count: setCard.count)
}
}
}
}
}