Swift Core Data:枚举Core Data [重复]

问题描述 投票:0回答:2

我正在尝试实现一个核心数据模型,该模型可以有效地镜像我从特定API中提取信息时使用的视图模型。我大部分内容都经过排序,但都在为一种属性而苦苦挣扎。有问题的属性是:

enum UnitType: String, Codable {
    case psi
    case kPa
    case litre
    case usg = "gallon"
    case kmph = "km/hour"
    case mph = "miles/hour"
    case celsius
    case fahrenheit
    case kgpmcubed = "kgpercubicmeter"
    case lbspusg = "lbsperusg"
    case lbspftcubed = "lbspercubicfeet"
    case apidensity
    case kg = "kilogram"
    case lbs = "pound"
}

我需要能够在此处设置枚举值,因为视图控制器使用此UnitType属性基于此枚举进行各种计算。如何使用核心数据创建枚举?本质上,我需要能够像这样设置此值:

MyEntity.unitType = viewModel.UnitType
swift xcode core-data enums
2个回答
1
投票

您无法在enum中存储CoreData类型,但是可以存储rawValue。由于您的枚举的rawValue为String类型,因此可以存储它的rawValue并使用枚举的enum方法转换回init,如下所示:

coreDataModel.unitType = viewModel.unitType.rawValue

和:

viewModel.unitType = UnitType(rawValue: coreDataModel.unitType)

注:从rawValue转换为enum类型时,它是可选的,因为String可以是任何东西,并且不能与case中提供的任何enum匹配。因此,将需要提供default值。


1
投票

很遗憾,您无法将枚举保存在CoreData中。

您可以在模型中具有String变量:

class MyEntity: NSManagedObject {
    @NSManaged public var unitType: String
}

然后您可以随时将其转换为您的UnitType。

myEntity.unitType = viewModel.UnitType.rawValue

viewModel.unitType = UnitType(rawValue: myEntity.unitType)!

© www.soinside.com 2019 - 2024. All rights reserved.