Monday, February 5, 2024

T? and Optional<T> Are Not the Same in Swift

Nick Lockwood:

I once again got bitten by the fact that T? properties in a Swift struct become optional parameters in the synthesized initializer, making it easy to accidentally omit a property that you meant to set.

The workaround is either to use let instead of var, or to use Optional<T> instead of T?

Swift has lots of syntactic sugar, which usually makes writing it simpler and easier, but sometimes multiple bits of sugar interact or obscure what’s going on.

Jonathan Joelson:

The fact that something is nullable does not remotely imply that null is a sensible default.

Comments RSS · Twitter · Mastodon

Leave a Comment