skip to content

When Swift imports an Objective-C header, how do nullability annotations, lightweight generics and NS_ENUM declarations decide the Swift types you get?

level: middleimportance: must knowfreq 58%

answer

  1. three nullability outcomes
  2. unannotated means unknown, not nullable
  3. typed collections versus Any
  4. NS_ENUM is open to new cases
  5. NS_OPTIONS becomes a set

basics

~20 s

Unannotated Objective-C pointers import as implicitly unwrapped optionals, nullable as optionals, nonnull as plain types; NSArray<NSString *> becomes [String] while a bare NSArray becomes [Any]; NS_ENUM becomes a non-frozen Swift enum and NS_OPTIONS an OptionSet struct.

solid answer

~40 s

Objective-C pointers carry no nullability unless the header says so. With no annotation, or `null_unspecified`, Swift imports an implicitly unwrapped optional such as `String!`; `nullable` gives `String?`; `nonnull`, or any pointer inside `NS_ASSUME_NONNULL_BEGIN`/`END`, gives plain `String`. Lightweight generics carry element types: `NSArray<NSString *> *` imports as `[String]`, `NSDictionary<NSString *, NSNumber *> *` as `[String: NSNumber]`, and an untyped `NSArray *` as `[Any]`. `NS_ENUM` becomes a Swift enum with prefix-stripped cases, but it is non-frozen, so a `switch` without `@unknown default` is a warning in Swift 5 mode and an error in Swift 6 mode; `NS_CLOSED_ENUM` imports frozen. `NS_OPTIONS` becomes a struct conforming to `OptionSet`, and a plain C enum a `RawRepresentable` struct with global constants. The annotations are promises Objective-C does not enforce.

code

swift · 20 lines
swift
// Imported from LegacyPhotoStore.h:
//   - (NSString *)titleForPhotoID:(NSString *)photoID;        // no annotation
//   NS_ASSUME_NONNULL_BEGIN
//   - (nullable NSString *)captionForPhotoID:(NSString *)photoID;
//   - (NSArray<NSString *> *)allPhotoIDs;
//   - (NSArray *)untypedTags;
//   NS_ASSUME_NONNULL_END
//   typedef NS_ENUM(NSInteger, PhotoFilter) { PhotoFilterNone, PhotoFilterSepia, PhotoFilterMono };

func describe(_ store: LegacyPhotoStore, filter: PhotoFilter) -> String {
  let title: String! = store.title(forPhotoID: "p1")
  let caption: String? = store.caption(forPhotoID: "p1")
  let ids: [String] = store.allPhotoIDs()
  let tags: [Any] = store.untypedTags()
  switch filter {
  case .none, .sepia, .mono: break
  @unknown default: break   // required in Swift 6 mode
  }
  return "\(title ?? "") \(caption ?? "") \(ids.count) \(tags.count)"
}

go deeper

for a junior

Recall the three nullability outcomes: no annotation gives an implicitly unwrapped optional, nullable an optional, nonnull a plain type.

for a middle

Explain how audit regions, lightweight generics, NS_ENUM and NS_OPTIONS each change the imported Swift type, and why NS_ENUM still needs @unknown default.

for a senior

Show that annotations are unenforced promises: a wrong nonnull fails in Swift far from its cause, so audit headers as carefully as code.

for a principal

Treat header annotation as migration work: annotating nullability, generics and enums before porting improves every Swift caller at once.

## Why the header decides When Swift imports an Objective-C header, through a bridging header or a framework's module, the Clang importer turns every declaration into a Swift one. Objective-C's type system is looser than Swift's: any object pointer may be `nil`, a collection holds `id`, and an enum is an integer that may carry values the header never listed. Swift therefore reads **annotations** in the header to decide how strict the imported type can be. A well-annotated header imports as idiomatic Swift; a bare one imports as defensive, awkward Swift. ## Nullability: three outcomes | Objective-C declaration | Imported Swift type | |---|---| | `NSString *` with no annotation, or `null_unspecified` | `String!` (implicitly unwrapped optional) | | `nullable NSString *` or `NSString * _Nullable` | `String?` | | `nonnull NSString *`, or any pointer inside `NS_ASSUME_NONNULL_BEGIN` ... `NS_ASSUME_NONNULL_END` | `String` | Key points: - **Unannotated means unknown, not nullable.** Swift picks the implicitly unwrapped optional so call sites stay terse, while any use that needs the plain value checks for `nil` and traps if it finds one. The details of how `String!` behaves once assigned belong to the material on optionals. - **Audit regions** are how real headers get annotated: wrap the whole header in `NS_ASSUME_NONNULL_BEGIN`/`END`, then mark the exceptions `nullable`. The same Clang qualifiers (`_Nonnull`, `_Nullable`, `_Null_unspecified`) apply to plain C pointers, which import as `UnsafePointer<T>`, `UnsafePointer<T>?` or `UnsafePointer<T>!`. - **The annotation is a promise, not a check.** Objective-C does not stop an implementation returning `nil` from a `nonnull` method; Swift trusts the header, so a wrong annotation surfaces as a failure on the Swift side, far from its cause. ## Lightweight generics Objective-C's lightweight generics exist only at compile time, but Swift reads them: - `NSArray<NSString *> *` imports as `[String]`, and `NSDictionary<NSString *, NSNumber *> *` as `[String: NSNumber]`. - An unparameterized `NSArray *` imports as `[Any]`, and `NSDictionary *` as `[AnyHashable: Any]`, which push casts onto every caller and turn a type mistake into a failed cast at run time instead of a compile error. - A custom Objective-C generic class imports as a Swift generic class, with limits: since its parameters are not represented at run time, an `as?` cast does not check them, and a Swift subclass must fix the parameters. ## Enums and option sets 1. **`NS_ENUM(NSInteger, PhotoFilter)`** imports as a Swift enum with `Int` raw values; the common prefix is stripped, so `PhotoFilterSepia` becomes `.sepia`. It is **non-frozen**: the library may add cases later, so an exhaustive `switch` still needs `@unknown default`. Without it the compiler warns in Swift 5 mode and errors in Swift 6 mode, where the `NonfrozenEnumExhaustivity` behaviour is on. 2. **`NS_CLOSED_ENUM`** (an enum declared with the `enum_extensibility(closed)` attribute) imports as a frozen enum, and an exhaustive `switch` needs no `@unknown default`. 3. **`NS_OPTIONS`** imports as a struct conforming to `OptionSet`, so you write `[.stripMetadata, .keepAlpha]`. 4. A **plain C enum** with no macro imports as a struct conforming to `RawRepresentable`, with each enumerator as a global constant, because C code may store any integer in it. ## Error parameters Objective-C reports failure through a trailing `NSError **` parameter, and the importer turns that convention into Swift error handling: - `- (BOOL)saveAlbum:(NSString *)name error:(NSError **)error;` imports as `func saveAlbum(_ name: String) throws`; the `BOOL` result disappears. - `- (nullable NSData *)exportAlbum:(NSString *)name error:(NSError **)error;` imports as `func exportAlbum(_ name: String) throws -> Data`: the `nullable` on the result only signals failure, so the Swift result is non-optional. How Swift code then catches the error belongs to the material on throwing and catching. ## Names The importer also renames: Objective-C selectors are split into Swift argument labels (`titleForPhotoID:` becomes `title(forPhotoID:)`), and `NS_SWIFT_NAME` in the header overrides the automatic name when it reads badly. ## Reviewing a header for Swift callers - Wrap it in an audit region and mark only the genuinely nullable pointers. - Parameterize every collection. - Use `NS_ENUM`, `NS_CLOSED_ENUM` or `NS_OPTIONS` instead of a bare `enum` or a `typedef` of `NSInteger`. - Give error-reporting methods the `NSError **` last parameter, so they import as throwing functions instead of returning flags. - Re-read the imported interface (Xcode can show the generated Swift interface of a header) after each change; one declaration left outside the audit region turns a clean `String` back into `String!` for every caller.

  • An Objective-C method declared nonnull returns nil at run time; what can the Swift caller expect?
    Nothing safe. Swift imported a non-optional type and trusts it, while Objective-C never enforced the annotation, so the `nil` arrives where Swift assumed a value and fails later, away from its cause. Fix the header by marking the result `nullable`, which changes the Swift type to an optional and makes every caller handle it.
  • Why does a plain C enum import as a struct rather than a Swift enum?
    C code can store any integer in an enum variable, including values the header never listed or bitwise combinations. A Swift enum assumes only its declared cases occur, so importing a plain C enum as one would be undefined behaviour. Swift imports it as a `RawRepresentable` struct with global constants; `NS_ENUM` or an `enum_extensibility` attribute opts into a real Swift enum.

  • An unannotated Objective-C pointer imports as a regular Swift optional.
  • NS_ASSUME_NONNULL makes the Objective-C compiler refuse to return nil.
  • A switch over an imported NS_ENUM never needs @unknown default.
  • NS_OPTIONS imports as a Swift enum with one case per flag.
  • A bare NSArray imports as [AnyObject] with its element type inferred.

Assumes Swift 6.4: a switch over an imported NS_ENUM without @unknown default is a warning in Swift 5 mode and an error in Swift 6 mode.