Author Topic: The best way to store/retrieve Swift enum values using Core Data  (Read 13789 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
Swift enumeration's raw values provide the functionality you need to convert enumeration values to/from integral values in Core Data.

First, you need to declare your enumeration with a raw value type:

Code: [Select]
enum GameMode: Int {
    case OnePlayer, TwoPlayers, Online
}

In your Core Data entity, create a computed property that acts as a wrapper around the entity property. In the following code, the gameModeSetting computed property is a wrapper for the gameMode entity property:

Code: [Select]
class SettingsEntity: NSManagedObject {

    @NSManaged private var gameMode: NSNumber
    @NSManaged var playerName: String
    @NSManaged var playerMark: String
   
    var gameModeSetting: GameMode {
        get {
            return GameMode(rawValue: self.gameMode.integerValue)!
        }
        set {
            self.gameMode = newValue.rawValue
        }
    }
}

The get method of the gameModeSetting computed property uses the rawValue initializer of the GameMode enumeration to convert the integer value to the enumeration value.

Going the other way, the set method of the gameModeSetting computed property converts the enumeration value to the integer value using the enumeration's rawValue property.

Also, notice the original gameMode property has been marked private so it's not accessible to code outside of the source code file in which it's declared.

You can use the gameModeSetting wrapper property to get and set the value like this:

Code: [Select]
let gameMode: GameMode = settingsEntity.gameModeSetting  // get the value
settingsEntity.gameModeSetting = GameMode.OnePlayer  // set the value

All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11
« Last Edit: August 25, 2015, 04:17:44 AM by kjmcneish »