I am using SwiftData in a SwiftUI view called DeckView and I'm adding a AddDeck function but let deck = Deck()
is returning 'Missing argument for parameter 'backingData' in call' Here is the full code:
DeckView
import SwiftUI
import SwiftData
struct DeckView: View {
@State private var showingSheet = false
@Environment(\.modelContext) var modelContext
@Query var decks: [Deck]
@State private var path = [Deck]()
var body: some View {
NavigationStack(path: $path) {
ZStack {
Color.background
.ignoresSafeArea()
List {
ForEach(decks) { deck in
NavigationLink(value: deck) {
HStack {
VStack(alignment: .leading) {
Text(deck.name)
HStack {
Image(systemName: "square.3.layers.3d.top.filled")
Text(deck.cards)
}
.padding(.top)
}
}
}
}
.onDelete(perform: deleteDeck)
.listRowBackground(Color(.secondaryC))
}
.scrollContentBackground(.hidden)
}
.foregroundColor(Color(.text))
.navigationTitle("Decks")
.navigationDestination(for: Deck.self, destination: EditDeckView.init)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Image(systemName: "plus")
.onTapGesture {
showingSheet.toggle()
addSamples()
}
}
}
.sheet(isPresented: $showingSheet) {
CreateDeckSheet()
}
}
}
func addSamples() {
let swiftd = Deck(name: "SwiftData", cards: "20")
let swifty = Deck(name: "Swift", cards: "21")
let swiftyui = Deck(name: "SwiftUI", cards: "32")
modelContext.insert(swiftd)
modelContext.insert(swifty)
modelContext.insert(swiftyui)
}
func addDeck() {
let deck = Deck()
modelContext.insert(deck)
path = [deck]
}
func deleteDeck(_ indexSet: IndexSet) {
for index in indexSet {
let deck = decks[index]
modelContext.delete(deck)
}
}
}
#Preview {
DeckView()
}
Data Model
import Foundation
import SwiftData
@Model
class Deck {
var name: String
var cards: String
init(name: String, cards: String) {
self.name = name
self.cards = cards
}
}