Search code examples
swiftxcodecore-dataoption-typeint32

Optional Int32 values in Core Data require unwrapping of optional Int32 values in code


In Core Data, attributes of type String and Int32 are "Optional" (ticked in properties).

enter image description here

Corresponding to these values in code, are the same types as optionals.

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

Values are set in some cases, and passed to a function, as optionals, for transfer to 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 compiles without error for the String? values, color1, color2 and color3, but shows the following error for Int32? values:

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

This suggests that the optional Int32 in CoreData is demanding an unwrapped optional value (while the optional Strings are fine)? Is there a difference (it would help me to understand why), and if so how is it best managed?

Assigning 'nil' as a starting value does not work. Force unwrapping causes a crash if nil (of course). Is it necessary to check for all values of type Int32?

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

Or should it be 'guard' or 'if let'?


Solution

  • Optional values in CoreData are not the same as in Swift. As per the comments, for numbers at least, set a mandatory - impossible value - instead of nil, and check this when using the value.