[swift-evolution] Swift null safety questions

David Waite david at alkaline-solutions.com
Sun Mar 12 15:56:26 CDT 2017


For bridged legacy code without nullability specifiers, IUOs basically save a few characters at the cost of potential crashing bugs. I’m believe there would have been a much stronger push to eliminate IUOs from the language before Swift 3 if this were the only use.

For legacy properties, there is null_resettable. These properties can never read nil, but they can be written with a nil to ‘reset’ them to some default value. We likely would need to replace this with some future property behaviors specification.

The most common use is in view controllers and other UI code due to the multi-phase initialization. The system will create the objects, then wire outlets, then once wiring is complete signal the view is ready. The outlets can all be nil during the wiring phase, but each wired outlet will be non-nil after wiring during actual usage. Dispersing unwrapping throughout the code for these outlets (and other properties initialized once the outlets are wired) would be a significant burden to clarity.

-DW

> On Mar 7, 2017, at 2: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.
> 
> A simple condition that a warning is emitted, except when unwrapping NSObject and its subclasses, or other unsafe operations like UnsafePointer, should cover all of its non-syntax uses. I think it is fair to say that developers would want to see the fatalError() written out.



More information about the swift-evolution mailing list