Skip to content

Instantly share code, notes, and snippets.

@kishikawakatsumi
Created July 17, 2023 07:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kishikawakatsumi/fbddf5d187fdab3a4399787201ca676b to your computer and use it in GitHub Desktop.
Save kishikawakatsumi/fbddf5d187fdab3a4399787201ca676b to your computer and use it in GitHub Desktop.
[SwiftData] Classes qualified with @model macro allow incomplete initializers
Classes qualified with @Model macro allow incomplete initializers
The compiler does not throw an error if a class with @Model, as in the following code, implements only an incomplete initializer (in this example, the properties are not initialized at all).
This would normally (if the plain class is not macro qualified) result in a compile error "Return from initializer without initializing all stored properties".
```swift
import SwiftData
@Model
final class Event {
var title: String
var start: Date
var end: Date
init(title: String, start: Date, end: Date) {
// This initializer does not initialize any properties
}
}
```
Properties that should be initialized are not, so the class will crash with a runtime error if any of the properties are accessed.
This behaviour in SwiftData breaks type safety.
This example is extreme, but consider another case where a property is added to an existing class, like the following:
```swift
@Model
final class Event2 {
var title: String
var start: Date
var end: Date
var isDeleted: Bool // Added this propety.
init(title: String, start: Date, end: Date) {
self.title = title
self.start = start
self.end = end
// Forgot to add initialize the property
}
}
```
If you then forget to add initialization for that property to the initializer, you have an error that is hard to notice and debug.
Classes qualified with @Model macros should have no different compile time behaviour than plain classes.
@kishikawakatsumi
Copy link
Author

Fix on iOS 17.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment