Bug: Generic type cannot check for nil

That familiarity is the point of the literal. Even today, Swift's primary use is interoperating with decades old Objective-C code, so there's necessarily some crossover in concepts between the languages.

1 Like

I see your point, but I also see a lot of Swift code where almost everything is an optional, perhaps because they are so convenient to type that it’s easier to let them spread throughout the code than to understand and deal with them properly, ie as early as possible.

Yeah. It's an easy default, especially for juniors or people from other languages which don't have a typed null representation, so it gets overused. Part of becoming an experienced Swift developer is learning to avoid optionals as much as possible. I don't think making them more painful to use in the language really helps with that goal, it just frustrates users, so the affordances Ben described are always going to be important.

6 Likes

Not just that; we don't live in a vacuum. Hopefully every day more developers with experience in other languages/no experience at all decide to learn Swift. It's important that we meet them where they are, as far as is reasonable.

nil or .none are very much like null in other languages. The difference with Swift is you don't need to worry about everything possibly being nil and crashing or returning garbage results. That's one of the first things people learn about Swift, and AFAICT, they love it.

Even in a generic context, when you only have a variable of type T, you rarely need to care about whether that's an optional and whether or not that variable is nil. It will still satisfy the generic constraints imposed upon it (in this case, no constraints - just some value), with well-defined semantics.

You could imagine making optional conform to Collection, where nil would be an empty collection. I'm not saying that would be a great design, but it would work and be well-defined, and code operating on the generic collection level would never need to care if value was an Array<Int> or Optional<Int>, or whether that optional was nil or not.

4 Likes

XDR, a data exchange format, encodes its version of Optional as an array with a length of zero or one. The in-memory encoding for the two are literally identical.

3 Likes

I must confess that I actually like this. It’s telling it like it is. And it makes people think before overusing or misunderstanding optionals. And I understand that I’m in minority.:relaxed: