[swift-evolution] [Pitch] Add Null struct to Foundation
David Rönnqvist
david.ronnqvist at gmail.com
Sun Jun 26 12:53:52 CDT 2016
I'm not convinced that Swift needs more than on way of representing the lack of a value. As far as I've understood (and remember), NSNull main reason to exist is that it's an actual object and won't for example terminate array literals. From what I've observed of people who are new to Objective-C, NSNull is a big surprise, both its general existence but also when to expect it (read check for NSNull to make sure one doesn't crash) and when not to.
The way I've imagined that the same problem would be solved in Swift is with an optional, optional value. That is: if a field in a response can either be set or not, that's an optional. If that field can either contain a value or the explicit lack of a value that's another optional:
let nickname: String?? = "Little Bobby Tables"
As I see it, this is both safer (requiring that the inner nil value is dealt with), serves as a documentation of when an explicit missing value is expected and when it's not, and is more consistent.
I would still expect a newcomer to wonder why there is two question marks in some places, but I'd imagine that that explanation would feel more logical.
And it's (still) possible (at least in the latest Swift Playground) to safely unwrap both levels:
if case let name?? = nickname { }
- David
Sent from my iPad
On 24 Jun 2016, at 11:32, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
>> Not really. What is the type of Optional.none? `let empty = Optional.none` does not compile, it says "Generic parameter 'Wrapped' could not be inferred". NSNull() is a unique concrete value, and it's compatible with Objective C, NSObject and AnyObject. We could of course use `Optional<Int16>.none`, but someone else may use `Optional<AnyObject>.none` instead. The extra type information is just misleading in this case.
>
> If you want a single, unique value, use `()`.
>
> But I'm not sure why you wouldn't just make this member an Optional<Any> in the first place. Is there some reason that wouldn't be suitable?
>
> --
> Brent Royal-Gordon
> Architechies
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list