1

I've run into an issue where setting a property on a SwiftData object to a Codable struct with an optional String crashes the app.

For example, if I have the following model object and struct :

@Model
final class Item {
    var timestamp: Date
    var codableProp: CodedValue?
    
    init(timestamp: Date, cProp: CodedValue?) {
        self.timestamp = timestamp
            self.codableProp = cProp
    }
}

struct CodedValue: Codable{
    var string0: String? = nil
    var bool0: Bool? = nil
    var bool1: Bool? = nil
}

If I create an instance of CodedValue with the following JSON, the app crashes:

{
    "bool0": true
}

The specific error I'm getting is:

"Could not cast value of type 'Swift.Optional<Swift.String>' (0x1c1e3f000) to 'Swift.String' (0x1c1e37e30)"

The crash seems to occur somewhere within the @Model macro: The expanded @Model macro, showing the line where the crash occurs

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Michael Berk
  • 365
  • 2
  • 16
  • Remove the `= nil` initialisers from your `CodedValue` struct – Paulw11 Jul 19 '23 at 01:16
  • After doing that, the issue still occurs – Michael Berk Jul 19 '23 at 01:56
  • How are you creating the instant of `CodedValue` from the Json? Where does it crash? Which line? – Paulw11 Jul 19 '23 at 05:28
  • Does it work at all to use custom types as property types in SwiftData currently? – Joakim Danielson Jul 19 '23 at 05:47
  • Custom Types are officially supported in SwiftData, provided they conform to Codable, as stated in the documentation (https://developer.apple.com/documentation/swiftdata/preservingyourappsmodeldataacrosslaunches) As for how I'm creating the `CodedValue`, I'm just using Swift's `JSONDecoder`: `let decoded = try JSONDecoder().decode(CodedValue.self, from: jsonString.data(using: .utf8)!)` – Michael Berk Jul 19 '23 at 15:33
  • That doesn’t mean it works since we’re using a beta version – Joakim Danielson Jul 19 '23 at 16:44

0 Answers0