Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the null-related property attributes in Xcode do?

With Xcode 6.3 I noticed some property attributes, namely:

  • nonnull
  • null_resettable
  • nullable

Could someone explain what they do when applied?

like image 722
Gee.E Avatar asked Apr 09 '15 07:04

Gee.E


1 Answers

Apple has added two new type annotations: __nullable and __nonnull. __nullable pointer may have a NULL or nil value, while a __nonnull one should not have.

As you should know in swift you can use optionals (?) but in Objective-C you cannot. Those attributes let you create Objective-C code which is more understandable by swift and complier warn you when you break the rule, for example:

@property (copy, nullable) NSString *name;
@property (copy, nonnull) NSArray *allItems;

This will be 'translated' in swift to:

var name: String?
var allItems: [AnyObject]!

This is taken from NSHipster:

nonnull: Indicates that the pointer should/will never be nil. Pointers annotated with nonnull are imported into Swift as their non-optional base value (i.e., NSData).

nullable: Indicates that the pointer can be nil in general practice. Imported into Swift as an optional value (NSURL?).

null_unspecified: Continues the current functionality of importing into Swift as an implicitly unwrapped optional, ideally to be used during this annotation process only.

null_resettable: Indicates that while a property will always have a value, it can be reset by assigning nil. Properties with a non-nil default value can be annotated this way, like tintColor. Imported into Swift as a (relatively safe) implicitly unwrapped optional. Document accordingly!

like image 145
Greg Avatar answered Oct 08 '22 02:10

Greg