Error when I try to instantiate @Model

I'm trying to instantiate my model and I'm getting an error on the set first property

import Foundation
import SwiftData

@Model final class PointModel {
  var x: CGFloat
  var y: CGFloat

  init(
    x: CGFloat,
    y: CGFloat
  ) {
    self.x = x
    self.y = y
  }
}

extension PointModel {
   static var preview: PointModel {
       PointModel(x: 0, y: 0)
   }
}
let point = PointModel(x: location.x, y: location.y)

{

    get {

        _$observationRegistrar.access(self, keyPath: \.x)

        return self.getValue(for: \.x)

    }



    set {

        _$observationRegistrar.withMutation(of: self, keyPath: \.x) {

          self.setValue(for: \.x, to: newValue) **Thread 1: Fatal error: Illegal attempt to use a nil as an Attribute - x + 151.0**

        }

    }

}

Has anyone else experienced this problem? Maybe someone knows how to solve this?

Replies

The problem only occurs when I try to save some numeric values. CGFloat, Int, Double. When I convert the desired values to String, then the error no longer occurs. Obviously, SwiftData still needs polishing

I just ran into this as well, and as @Nizelan is saying this occurs when you use a type that is not a valid Swift Data Type.

The valid swiftData types are

Int8, -128, 127
Int16, -32768, 32767
Int32, -2.1 x 109, 2.1 x 109
Int64, -9.2 x 1018, 9.2 x 1018
UInt8, 0, 255
UInt16, 0, 65535
UInt32, 0, 4.3 x 109
UInt64, 0, 1.8 x 1019
Double, -1.8 x 10308, 1.8 x 10308
Float, -3.4 x 1038, 3.4 x 1038
```[source](https://subscription.packtpub.com/book/programming/9781789534313/1/ch01lvl1sec14/swift-data-types)

I fixed this by using Float instead of CGFloat


  • Please ignore the above comment this didn't actually solve my issue I changed my code to use Float instead of CGFloat and still ran into the same error :(

Add a Comment