`ModelContext.registeredModel(for:)` crashes when generic type does not match actual type

Originator:darren.mo
Number:rdar://FB13472315 Date Originated:2023-12-16
Status:Open Resolved:
Product:SwiftData Product Version:iOS 17.2 RC Seed (21C62)
Classification:Incorrect/Unexpected Behavior Reproducible:Always
 
I have attached a sample project demonstrating the use of `ModelContext.registeredModel(for:)` to get already-fetched models. The method crashes when the generic type does not match the actual type as shown in the sample project:
```
private func track(for trackID: PersistentIdentifier) -> Track? {
   // Crashes when `registeredModel` tries to force cast a `MusicVideo` instance to `Song`.
   if let song: Song = modelContext.registeredModel(for: trackID) {
      return .song(song)
   }

   if let musicVideo: MusicVideo = modelContext.registeredModel(for: trackID) {
      return .musicVideo(musicVideo)
   }

   return nil
}
```

`ModelContext.registeredModel(for:)` tries to force cast the model instance to the generic type. This is unnecessary since the method returns an optional. Rather than crashing, the method should just return `nil` if the type did not match by using a conditional cast instead of a force cast.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!