-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathSwiftDataExample.swift
More file actions
83 lines (69 loc) · 2.06 KB
/
Copy pathSwiftDataExample.swift
File metadata and controls
83 lines (69 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// SwiftDataExample.swift
// Example
//
// SwiftData example setup for DebugSwift testing
//
import Foundation
import DebugSwift
#if canImport(SwiftData)
import SwiftData
@available(iOS 17.0, *)
@Model
final class SwiftDataPerson {
var name: String
var age: Int
var createdAt: Date
init(name: String, age: Int, createdAt: Date = Date()) {
self.name = name
self.age = age
self.createdAt = createdAt
}
}
@available(iOS 17.0, *)
@MainActor
final class SwiftDataExample {
static let shared = SwiftDataExample()
private init() {}
lazy var modelContainer: ModelContainer = {
do {
return try ModelContainer(for: SwiftDataPerson.self)
} catch {
fatalError("Unable to create SwiftData model container: \(error)")
}
}()
func setupDebugSwift() {
let models: [SwiftDataModelRegistration] = [
.init(SwiftDataPerson.self, displayName: "SwiftData Person") {
SwiftDataPerson(
name: "New Person",
age: Int.random(in: 18...65)
)
}
]
DebugSwift.Resources.shared.configureSwiftData(contexts: [
.init(name: "Main", container: modelContainer, models: models)
])
}
func createSampleDataIfNeeded() {
let context = modelContainer.mainContext
let descriptor = FetchDescriptor<SwiftDataPerson>()
do {
let existing = try context.fetch(descriptor)
guard existing.isEmpty else { return }
for i in 1...5 {
let person = SwiftDataPerson(
name: "SwiftData Person \(i)",
age: 20 + i,
createdAt: Date().addingTimeInterval(TimeInterval(-i * 3_600))
)
context.insert(person)
}
try context.save()
print("✅ Sample SwiftData created successfully")
} catch {
print("❌ Failed to setup SwiftData sample data: \(error)")
}
}
}
#endif