Alexdrob
Alexdrob

Reputation: 97

Enum with associated values in Core Data

Is it possible to store an enum with associated values using CoreData? I can't find any relevant solution. For example, a model for storing has a field of type Activity.

enum Activity {
  case bored
  case running(destination: String)
  case talking(topic: String)
  case singing(volume: Int)
}

Upvotes: 0

Views: 157

Answers (1)

MartinM
MartinM

Reputation: 937

There is no out of the box solution. CoreData can only save data types that can be represented with in Objective-C.

So you have to care about a conversion that can be used to store and retrieve the value, as a simple string for example:

case singing(volume: Int) -> "singing_volume_30"

Add RawRepresentable protocol conformance to the enum and implement constructor and rawValue property using pattern matching.

Another option would be to extract the Activity enum as own entity and use it as a relationship on the other entity where you try to access the Activity enum field.

Upvotes: 1

Related Questions