[swift-evolution] Swift null safety questions

David Sweeris davesweeris at mac.com
Mon Mar 13 18:36:14 CDT 2017

> On Mar 7, 2017, at 1:29 PM, Elijah Johnson via swift-evolution <swift-evolution at swift.org> wrote:
> Correct me if I am wrong, but it seems like the main intended use of optionals would be to work with legacy Obj-C code that is missing nullability specifiers. In the rest of the cases, a forced-unwrap is just "syntactic sugar" for a fatal error block or a way to indicate that you have already checked the type using "as" or "!= nil" (ie. that they wrote the code in a non-Swift style and haven't updated it yet - just the perfect situation for a warning).
> Another use is interoperability with "C" code, where the user knows that the code does not return a "null" pointer but has no way of annotating that in C. Or with arrays where the result is optional, but never is when the index is right. Maybe an @allowsForceUnwrap annotation on the function could silence this warning. Definitely a much more serious a condition that where the result of the function call goes unused.

Or when an operation might fail, but it isn’t worth going through a full do/try/catch dance. Indexing into dictionaries with invalid keys, for example… There’s only one way it can fail (no value associated with that key), and there’s no simple way to prove an index will be valid ahead of time, so the lookup returns an optional. There was a discussion probably  about 2-4 months back that went into it a fair bit, but I don’t recall what the thread’s actual topic was.

If Swift gets dependent types, I suspect the next day there'll be roughly 417 proposals suggesting we use them to create non-optional versions of nearly every stdlib function that currently returns an optional :-)

- Dave Sweeris

More information about the swift-evolution mailing list