How to import Objective-C types as optionals or non-optionals into Swift
Learn how to use nullability declarations and macros.
30 Jan 2023 · 3 min read
When working on a project that consists of a mixed code base, we might need to import and use Objective-C code in Swift files. Since every object in Objective-C can become nil, Swift imports every type as an implicitly unwrapped optional without any nullability annotations.
To be more expressive in Swift by using either optional or non-optional types, we have the possibility to extend the Objective-C code with nullability declarations and macros.
Let's look at how to do that.

Nullability declarations
We can annotate Objective-C code to indicate whether an instance can have a nil value. Swift uses those annotations to import declarations either as optional or non-optional:
- types with a nonnullable annotation are imported as non-optionals
- types with a nullable annotation are imported as optionals
- (nullable Tea *)search:(nonnull NSString *)name;
The example above is imported to Swift as follows:
search(name: String) -> Tea?
Without a nullability annotation, Swift would import a type as an implicitly unwrapped optional, which would look as follows:
search(name: String!) -> Tea!
Nullability macros
Additionally, we can use the macros NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END to annotate regions in Objective-C as nonnullable.
This can simplify the process of annotating Objective-C code if we'd like to import most of the types as non-optionals into Swift.
NS_ASSUME_NONNULL_BEGIN@interface SomeClass : NSObject- (nullable String *)subtitleForItem:(SomeItem *)item;@property NSString *title;@property NSArray<SomeItem *> *items;@endNS_ASSUME_NONNULL_END
In the example above, all types will be imported as non-optionals into Swift, except those we annotated with a nullable declaration.

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips