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 }
}
}


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.
... == niltests the outermost level.