swiftswift-optionals

Checking if Optional<Int> is nil


Help me understand this weird nil-check.

I have a variable of the type Int? and I need to switch on nil.

This makes sense:
enter image description here
buildFrameId is 3 and not equal to nil

This does not:
enter image description here
buildFrameId is nil and still not equal to nil

How do I check (single line statement) if buildFrameId is equal to nil?


Solution

  • While @martin-r led me to the reason for this behaviour, I came up with a solution my self.

    The "problem" is that I'm declaring the variable as nested optional:

    var buildFrameId: Int??
    

    This is needed in order for the JSONEncoder to actually encode the nil-property as null instead of omitting it.

    The solution is to flatten the nested optional - then normal unwrapping works. I used the proposed solution from this article: https://brodigy.medium.com/nested-optionals-in-swift-design-mistake-by-apple-7240ea61edd

    Here is the code for a flattening extension:

    extension Optional {
        public func flatten<Result>() -> Result?
        where Wrapped == Result?
        {
            return self.flatMap { $0 }
        }
    }
    

    enter image description here

    enter image description here

    It still doesen't feel that well, but it's better than the proposed solutions in the link provided by @roy-rodney. Encode nil value as null with JSONEncoder