核心数据中的可选Int32值需要解开代码中的可选Int32值

时间:2019-05-28 08:58:17

标签: swift xcode core-data optional int32

在Core Data中,String和Int32类型的属性为“可选”(在属性中标记)。

enter image description here

与代码中的这些值相对应,其类型与可选类型相同。

        var color1: String?
        var color2: String?
        var color3: String?
        var colorRangeLoc1: Int32?
        var colorRangeLoc2: Int32?
        var colorRangeLoc3: Int32?

在某些情况下会设置值,并将其作为可选参数传递给函数,以传输到Core Data。

func loadCellData(text: String, sortOrder: Int32, portion: Float, color1: String?, color2: String?, color3: String?, colorRangeLoc1: Int32?, colorRangeLoc2: Int32?, colorRangeLoc3: Int32?, colorRangeLen1: Int32?, colorRangeLen2: Int32?, colorRangeLen3: Int32?, underlineRangeLoc1: Int32?, underlineRangeLoc2: Int32?, underlineRangeLoc3: Int32?, underlineRangeLen1: Int32?, underlineRangeLen2: Int32?, underlineRangeLen3: Int32?)
{
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let entry: CellData = NSEntityDescription.insertNewObject(forEntityName: "CellData", into: context) as! CellData

    entry.text = text
    entry.sortOrder = sortOrder
    entry.portion = portion
    entry.color1 = color1
    entry.color2 = color2
    entry.color3 = color3
    entry.colorRange1Loc = colorRangeLoc1
    entry.colorRange2Loc = colorRangeLoc2
    entry.colorRange3Loc = colorRangeLoc3
...

Xcode是否为String编译而没有错误?值color1,color2和color3,但是对于Int32显示以下错误?值:

Value of optional type 'Int32?' must be unwrapped to a value of type 'Int32'

这表明CoreData中的可选Int32是否要求一个未包装的可选值(而可选字符串则可以)?有什么区别(它可以帮助我理解原因),如果可以的话,如何对其进行最佳管理?

将“ nil”指定为起始值不起作用。如果为nil,则强制展开会导致崩溃(当然)。是否需要检查Int32类型的所有值?

if colorRangeLoc1 != nil { entry.colorRangeLoc1 = colorRangeLoc1 }

还是“守卫”还是“如果放任”?

2 个答案:

答案 0 :(得分:0)

CoreData中的可选值与Swift中的可选值不同。根据注释,至少要为数字设置一个必需的-不可能的值-而不是nil,并在使用该值时进行检查。

答案 1 :(得分:0)

public var parent: Int32? {
    get {
        willAccessValue(forKey: "parent")
        defer { didAccessValue(forKey: "parent") }
        return primitiveValue(forKey: "parent") as? Int32
    }
    set {
        willChangeValue(forKey: "parent")
        defer { didChangeValue(forKey: "parent") }
        guard let value = newValue else {
            setPrimitiveValue(nil, forKey: "parent")
            return
        }
        setPrimitiveValue(value, forKey: "parent")
    }
}