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:
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:
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:
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