https://github.com/cuadros-code/project-11-swiftui-book-worm
Project 11 book history
https://github.com/cuadros-code/project-11-swiftui-book-worm
Last synced: 8 months ago
JSON representation
Project 11 book history
- Host: GitHub
- URL: https://github.com/cuadros-code/project-11-swiftui-book-worm
- Owner: cuadros-code
- Created: 2025-01-11T21:41:31.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-01-16T15:59:48.000Z (over 1 year ago)
- Last Synced: 2025-01-16T16:43:16.827Z (over 1 year ago)
- Language: Swift
- Size: 1.78 MB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# SwiftData
## step by step
- Create model
```swift
import Foundation
import SwiftData
@Model
class Student {
var id: UUID
var name: String
init(id: UUID, name: String) {
self.id = id
self.name = name
}
}
```
- Add model container to View
```swift
.modelContainer(for: Student.self)
```
- Use model context and Query to use data from SwiftData
```swift
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@Query var students: [Student]
var body: some View {
NavigationStack {
List(students) { student in
Text(student.name)
}
.navigationTitle("Classroom")
.toolbar {
Button("Add") {
let firstNames = ["Kevin", "Julio", "Luz"]
let lastNames = ["Mora", "Cuadros", "Ferrari"]
let chosenFirstName = firstNames.randomElement()!
let chosenLastName = lastNames.randomElement()!
let student = Student(
id: UUID(),
name: "\(chosenFirstName) \(chosenLastName)"
)
modelContext.insert(student)
}
}
}
}
}
```
- Sort Using Query
```swift
@Query(sort: \Book.rating, order: .forward) var books: [Book]
```