Error saving @Model with enum

Hey,

I am trying to save an enum in my model with SwiftData but getting a weird error message I do not understand at the moment, and I am pretty sure I am missing something here.

public enum URLScheme: String, Codable {
  case https
  case http
}

@Model
public class MyModel {
  public var urlScheme: URLScheme
}

When I try to save the model I get the following error message in the console:

error: Row (pk = 1) for entity 'MyModel' is missing mandatory text data for property 'https'

I was wondering if I need to tell SwiftData how to save my enum ? My assumption was that I can save any enum if it conforms to Codable. Am I doing something wrong here or is this a beta bug ?

Thanks a lot for helping

Post not yet marked as solved Up vote post of alexanderwe Down vote post of alexanderwe
2.7k views

Replies

I ran into the same thing and my guess is that it's a bug. (Filed as feedback FB12247784.) For the time being I worked around it by switching my enum's raw values from String to Int.

  • @tschmitz Thanks for submitting the feedback already. But then it's not me alone. I also went with storing raw data for now and having an optional computed property in the model which converts the raw data into the enum type.

  • Even using an Int as the raw value doesn't work for me. It will work while using the app, but after closing or re-running the app, the enum will just use a zero integer value instead of loading up what was stored before.

  • Same error here. The app is crashing once we try to perform a read after a save operation.

This is mentioned in the release notes of iOS 17: https://developer.apple.com/documentation/ios-ipados-release-notes/ios-ipados-17-release-notes

Case value is not stored properly for a string rawvalue enumeration. (108634193)

Workaround: Don’t use a rawvalue with a string enum property.

  • Can confirm, it finally works! Tested with Xcode 15 Beta 7.

Add a Comment

I can also confirm it works now correctly :)

@alexanderwe Has anyone tried using enum inside the Query predicate? For me enum gets saved however doesn't work with Query Refer https://developer.apple.com/forums/thread/737929