SwiftUI and Core Data optionals
If you have used Swift before, you are familiar with Optionals
, but it is handled much differently when it comes to Core Data. If you uncheck the Optional checkbox in Attributes inspector, it will still be generated as an optional Swift property. Core Data only cares that properties have values when saved and can be nil
at other times. There are different ways to handle this, but I found the most elegant way was to create an extension in the Optional
class. If you look inside the Utilities
folder, you will see three files — IntOptional.swift
, BoolOptional.swift
, and StringOptional.swift
. Each of these files is structured the same way, but they work for Int
, Boolean,
and String
, respectively.
Let's look at StringOptional.swift
in a little more detail using the following code:
Now with this file, we can make our code a bit shorter:
- We do not have to do something like this in our code:
Image(self...