Created
July 17, 2023 07:56
-
-
Save kishikawakatsumi/fbddf5d187fdab3a4399787201ca676b to your computer and use it in GitHub Desktop.
[SwiftData] Classes qualified with @model macro allow incomplete initializers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fix on iOS 17.1.