-1

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?

4
  • 3
    You have a nested optional and ... == nil tests the outermost level. Commented Jun 27, 2024 at 11:58
  • You are right @MartinR. It's declared like this var buildFrameId: Int?? in order to achieve that a nil-value is JSON encoded to "buildFrameId": null. having only one optional-sign omits the property when JSON encoded. Any ideas on how to double unwrap or avoid the ?? Commented Jun 27, 2024 at 12:42
  • @esbenr stackoverflow.com/questions/47266862/… Commented Jun 27, 2024 at 13:08
  • @RoyRodney Thanks for the link, My solution is exactly the first answer - if you check the comments, I also commented. There are many creative suggestions in that thread - all of them (besides the ??) are an eyesore. At least it should be possible to configure the JSONEncoder to do this. Commented Jun 27, 2024 at 14:54

1 Answer 1

0

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

  • I don't know why someone down voted the question - I guess it would have been a bit more helpful with a comment on why.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.