Post

SwiftData One-To-Many

SwiftData One-To-Many

How to create one-to-many relationships

  1. If you intend to use inferred relationships, one side of your data must be optional.
  2. If you use an explicit relationship where one side of your data is non-optional, be careful how you delete objects - SwiftData uses the .nullify delete rule by default, which can put your data into an invalid state. To avoid this problem, either use an optional value, or use a .cascade delete rule.
  3. Do not attempt to use collection types other than Array, because your code will simply not compile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Model class Movie {
	var name: String
	var releaseYear: Int  
	var director: Director?

	init( ...
}

@Model class Director {
	var name: String
	@Relationship(deleteRule: .nullify, inverse: \Movie.director) var movies: [Movie]
	
	init( ...
}
This post is licensed under CC BY 4.0 by the author.