Nullability & Lightweight Generics
Since 2015, Objective-C headers can carry two kinds of extra type information: nullability (may this pointer be nil?) and lightweight generics (what's inside this collection?). Neither changes how the program runs. They add compiler warnings and, very importantly, they decide how your API looks in Swift.
Nullability annotations
| Annotation | Meaning |
|---|---|
nonnull / _Nonnull |
never nil |
nullable / _Nullable |
may be nil |
null_unspecified |
unknown (the old default) |
Inside NS_ASSUME_NONNULL_BEGIN … NS_ASSUME_NONNULL_END, every pointer is nonnull unless you mark it nullable. Apple's headers use this everywhere, and so should yours:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface UserProfile : NSObject
@property (nonatomic, copy) NSString *username; // nonnull
@property (nonatomic, copy, nullable) NSString *nickname; // may be nil
- (instancetype)initWithUsername:(NSString *)username;
- (NSString *)displayName;
- (nullable NSString *)initials; // returns nil if unknown
@end
NS_ASSUME_NONNULL_END
@implementation UserProfile
- (instancetype)initWithUsername:(NSString *)username {
self = [super init];
if (self) { _username = [username copy]; }
return self;
}
- (NSString *)displayName {
return self.nickname ?: self.username;
}
- (NSString *)initials {
if (self.nickname.length == 0) {
return nil;
}
return [[self.nickname substringToIndex:1] uppercaseString];
}
@end
int main(void) {
@autoreleasepool {
UserProfile *p = [[UserProfile alloc] initWithUsername:@"jdoe"];
NSLog(@"%@, initials %@", [p displayName], [p initials] ?: @"-");
p.nickname = @"jamie";
NSLog(@"%@, initials %@", [p displayName], [p initials]);
}
return 0;
}jdoe, initials -
jamie, initials J
In Swift, this class appears with username: String and nickname: String?, and initials() returns String?. Without annotations, everything would be an implicitly unwrapped String!.
The compiler catches nil mistakes
Passing a literal nil where nonnull is expected produces a warning. The warning text below is part of the output, printed before the program runs:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Greeter : NSObject
- (NSString *)greet:(NSString *)name;
@end
NS_ASSUME_NONNULL_END
@implementation Greeter
- (NSString *)greet:(NSString *)name {
return [NSString stringWithFormat:@"Hello, %@!", name];
}
@end
int main(void) {
@autoreleasepool {
Greeter *g = [Greeter new];
NSLog(@"%@", [g greet:@"Ana"]);
NSLog(@"%@", [g greet:nil]); // warning: null passed to a nonnull parameter
}
return 0;
}main.m:19:25: warning: null passed to a callee that requires a non-null argument [-Wnonnull]
NSLog(@"%@", [g greet:nil]); // warning: null passed to a nonnull parameter
^ ~~~
1 warning generated.
Hello, Ana!
Hello, (null)!
It still runs (formatting nil gives (null)), because nullability is a promise checked at compile time, not a run-time guard.
Lightweight generics
Collections can declare their element types in angle brackets: NSArray<NSString *> *, NSDictionary<NSString *, NSNumber *> *. The compiler then knows what array[0] returns and warns when you insert the wrong type:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSArray<NSString *> *fruits = @[@"fig", @"lime"];
NSMutableDictionary<NSString *, NSNumber *> *prices = [NSMutableDictionary dictionary];
for (NSString *f in fruits) {
prices[f] = @(f.length * 0.5);
}
NSString *first = fruits.firstObject; // no cast needed
NSLog(@"%@ costs %@", first, prices[first]);
NSLog(@"lime is %lu characters", (unsigned long)fruits[1].length); // typed element
NSMutableArray<NSString *> *names = [NSMutableArray array];
[names addObject:@"Uma"];
[names addObject:@42]; // warning: wrong element type
NSLog(@"%lu names (generics don't stop it at run time)", (unsigned long)names.count);
}
return 0;
}main.m:17:26: warning: incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *' [-Wincompatible-pointer-types]
[names addObject:@42]; // warning: wrong element type
^~~
/usr/local/include/Foundation/NSArray.h:316:48: note: passing argument to parameter 'anObject' here
- (void) addObject: (GS_GENERIC_TYPE(ElementT))anObject;
^
1 warning generated.
fig costs 1.5
lime is 4 characters
2 names (generics don't stop it at run time)
Note fruits[1].length: without generics, fruits[1] is id and dot syntax on id doesn't compile. Generics are "lightweight" because they're erased after compilation: at run time an NSArray<NSString *> is just an NSArray, which is why the number was still added.
Your own generic classes
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Stack<ObjectType> : NSObject
- (void)push:(ObjectType)object;
- (nullable ObjectType)pop;
- (nullable ObjectType)peek;
@property (nonatomic, readonly) NSUInteger count;
@end
NS_ASSUME_NONNULL_END
@implementation Stack {
NSMutableArray *_items;
}
- (instancetype)init {
self = [super init];
if (self) { _items = [NSMutableArray array]; }
return self;
}
- (void)push:(id)object { [_items addObject:object]; }
- (id)pop {
id top = _items.lastObject;
if (top) [_items removeLastObject];
return top;
}
- (id)peek { return _items.lastObject; }
- (NSUInteger)count { return _items.count; }
@end
int main(void) {
@autoreleasepool {
Stack<NSString *> *history = [Stack new];
[history push:@"home"];
[history push:@"settings"];
[history push:@"privacy"];
NSLog(@"top: %@ (%lu pages)", [history peek], (unsigned long)history.count);
NSLog(@"back from %@", [history pop]);
NSLog(@"back from %@", [history pop]);
NSLog(@"now on %@ (uppercase %@)", [history peek], [history peek].uppercaseString);
[history pop];
NSLog(@"empty pop: %@", [history pop]);
}
return 0;
}top: privacy (3 pages)
back from privacy
back from settings
now on home (uppercase HOME)
empty pop: (null)
Inside @implementation, the type parameter isn't available, so the methods are written with id.
| Feature | Swift import |
|---|---|
nonnull NSString * |
String |
nullable NSString * |
String? |
unannotated NSString * |
String! |
NSArray<NSString *> * |
[String] |
unannotated NSArray * |
[Any] |
NSDictionary<NSString *, NSNumber *> * |
[String: NSNumber] |
Test yourself
Inside NS_ASSUME_NONNULL_BEGIN/END, how do you allow a property to be nil?
- Mark it weak
- Mark it nullable
- Mark it optional
- It's already allowed
What happens at run time when you add an NSNumber to an NSMutableArray<NSString *>?
- An exception
- It's added: generics are compile-time only
- It's converted to a string
- It's silently ignored
How does nullable NSString * appear in Swift?
- String
- String?
- String!
- NSString