SwiftData by Example: iOS 17 & SwiftUI 5 — Part 5

DevTechie
DevTechie
Published in
4 min readOct 4, 2023

--

SwiftData by Example: iOS 17 & SwiftUI 5 — Part 5

Books are categorized into literary genres, and therefore, it would be logical for our book log to include a genre classification to help us keep track of the number of fictional and non-fictional books we’ve read.

Given that a genre can have many books, and conversely, a book can be associated with multiple literary genres, this scenario offers an excellent opportunity to test how SwiftData manages a many-to-many (N:N) relationship.

We will start by adding a new model to our project.

import Foundation
import SwiftData

@Model
final class Genre {
var name: String
var books = [Book]()

init(name: String) {
self.name = name
}
}

Let’s also update the book model to include the relationship between Genre and Book models.

The relationship between Book and Genre will employ a nullify delete rule, essentially nullifying the related model’s reference to the deleted model. By defining this delete rule, we ensure that when a book is deleted, the genre category should not be deleted.

import Foundation
import SwiftData

@Model
final class Book {
...

@Relationship(deleteRule: .nullify, inverse: \Genre.books)
var genres = [Genre]()

init(title: String, author: String, publishedYear: Int) {…

--

--