4.5 · Nullability, lightweight generics, Swift-friendly names
A bare Objective-C header tells Swift almost nothing about optionality or element types. A few annotations turn a clumsy import into an API that reads like Swift.
Mental model. Annotate the header, not the implementation. What you declare there decides every Swift caller’s types, and the compiler cannot check the promise for you.
Types that import cleanly
Nullability and element types.
- How do nullability annotations change what Swift sees, and what happens when they lie?
Objective-C pointers can always be nil, so Swift needs to be told which ones can be. nonnull imports as T, nullable as T?, and null_resettable as T! for… - What are lightweight generics, and what do they not do?
Objective-C collections can carry an element type in the declaration: NSArray<NSString *> *, NSDictionary<NSString *, NSNumber *> *. Swift imports these as…
Naming for Swift
Renaming and shaping an Objective-C API for its Swift callers.
- How do you make an Objective-C API feel native in Swift?
Swift imports Objective-C by mechanical rules, which can produce awkward names. You can shape the result from the header. NS_SWIFT_NAME(total(items:)) renames…
More in Objective-C & interop
- 4.1 · Message send, selectors, forwarding, isa
- 4.2 · Categories, associated objects, load and initialize
- 4.3 · NSObject, class clusters, copying
- 4.4 · @objc, what does not bridge, and error bridging
- 4.6 · Method swizzling, and when it is a footgun
- 4.7 · Reading Objective-C, blocks, and manual reference counting
- 4.8 · Mixed-language projects, costs, and migrating a large app
- 4.9 · How Objective-C declarations arrive in Swift
- 4.10 · The runtime up close: introspection, encodings, IMPs and exceptions
- 4.11 · Key-value coding and observing
- 4.12 · What crosses the boundary: inference and concurrency