Swift 1.2: Working with __nullable and __nonnull


Xcode 6.3 and Swift 1.2 brought about a sleuth of new features and changes, none-more prominant than  Nullability Annotations. Swift provides great distinction between optionals and non-optionals, as you noticed when you began to get accustomed to the language. 

 NSString? and NSString are treated as different types per-se, and you would only be able to inter-operate between them through wrapping and un-wrapping, which makes for safer coding. This distinction was lacking however in the predecessing Objective-C, which was constrained to representing the type as NSString*. When working with Objective-C libraries in Swift, not being able to distinct between optionals and non-optionals forced the language to forcably unwrap the NSString as an optional NSString!.  Enter __nullable and __nonnull

What is __nullable and __nonnull?

The first annotation pointer, __nullable permits the object to be denoted as either be NULL or nil, whereas __nonnull is non-null.  

In the above example, prior to Swift 1.2, we would have had the app crash, as the serial integer cannot be nil, due to it's signature as a non-optional earlier on.


 func serialAssignmentForCat(cat: Cat, forSerial serial: Int?) {


 snuggles.assignOwnerForCat(cat, withSerial: serial) 


In the latest Swift update, we don't declare serial as serial! in the Pet class function, as Swift will work out whether it is null or not. We would therefore get a warning rather than a crash, to remind us.

In the Objective-C example, we could declare, in the method call something like:

forSerial:(nullable NSNumber*)serial  

This would then signal to us if we imported the Objective-C code into Swift whether we should treat it as optional or non-optional. I think this is a great improvement and makes writing safe-code, safer when working cross-language.