Я определил следующие модели в приложении Swift для iOS:
Код: Выделить всё
import Foundation
import SwiftData
@Model
class User: Identifiable {
let id: UUID
let name: String
var location: NamedLocation?
var friend: Bool = false
init(id: UUID = UUID(), name: String) {
self.id = id
self.name = name
}
}
struct NamedLocation: Codable {
let name: String?
let loc: Location
init(name: String?, location: Location) {
self.name = name
self.loc = location
}
}
enum Location: Codable {
case address(String)
case coordinates(Double, Double)
}
works fine:
Код: Выделить всё
import SwiftUI
import SwiftData
struct HomeView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [User]
var body: some View {
// other views omitted for brevity
VStack(alignment: .leading, spacing: 16.0) {
Text("your nearby friends")
List {
ForEach(items) { item in
HStack {
VStack {
Text(item.name)
if let location = item.location {
Text(location.name ?? "unknown location")
}
}
}
}
}
.listStyle(.plain)
.scrollContentBackground(.hidden)
Spacer()
}
}
}
#Preview {
let config = ModelConfiguration(isStoredInMemoryOnly: true, allowsSave: true)
let container = try! ModelContainer(for: Schema([User.self]), configurations: config)
for i in 1..
Источник: [url]https://stackoverflow.com/questions/78133560/swiftdata-crashes-on-trying-to-access-struct-property[/url]