Skip to content
tezvyn:

Lightweight Generics: Type Safety for Objective-C

Source: developer.apple.comMediumHow cards are made

Lightweight Generics: Type Safety for Objective-C

Lightweight generics bolt type safety onto Objective-C collections like NSArray. This lets Swift see an NSArray<NSString *> as a type-safe [String] instead of [Any], preventing runtime crashes.

Why it exists

Before Swift, Objective-C collections like NSArray were untyped; they held objects of type id. When Swift was introduced, these collections were bridged as [Any], forcing developers to constantly cast and check types, which was unsafe and verbose. Lightweight generics were added to Objective-C to solve this interoperability problem.

The mental model

Think of lightweight generics as a contract or a hint for the compiler, especially the Swift compiler. You're telling the system, "I promise this array will only contain strings." The compiler then uses this promise to provide type safety and better autocompletion, but it doesn't build a runtime wall to enforce it within Objective-C itself. It's a compile-time annotation for better code, not a runtime feature.

How it works

You add a type parameter in angle brackets to Objective-C collection classes. For example, a plain NSArray becomes NSArray<NSString > *. When the Swift compiler imports this header, it sees the generic type and bridges the NSArray as a Swift native Array<String> (or [String]). This works for NSArray, NSDictionary, and NSSet, as well as your own custom Objective-C classes. You can also define bounds on your generic types, like T: NSNumber, to require that the type is a subclass of NSNumber.

When to use it

Use lightweight generics in any modern Objective-C code that might be called from Swift. It's standard practice for any new Objective-C APIs. It dramatically improves the developer experience for Swift consumers of your code, making the API safer, more predictable, and self-documenting. It's essential for maintaining a clean codebase that mixes both languages.

When not to use it

Avoid them if you genuinely need a heterogeneous collection where the types are unknown until runtime. In such cases, forcing a generic type would be misleading. For pure Objective-C projects that will never interact with Swift, they provide less value, but are still good practice for clarity.

One canonical example

An Objective-C method signature without generics might be (NSArray )fetchUserIDs;. Swift would see this as func fetchUserIDs() -> [Any]. The Swift developer would have to cast every element. With lightweight generics, the signature becomes (NSArray<NSString > *)fetchUserIDs;. Swift now sees this as func fetchUserIDs() -> [String]. The API is now type-safe, and no casting is needed on the Swift side.

Interview question

What is the main advantage of applying Lightweight Generics to Objective-C collections when bridging to Swift?

  • a.It ensures that Objective-C collections strictly enforce type constraints at runtime.
  • b.It enables Objective-C to directly use Swift's advanced generic protocols and associated types.
  • c.It automatically converts Objective-C's untyped collections into Swift's value-typed structs for better memory management.
  • d.It allows Swift to treat Objective-C collections as type-safe arrays, eliminating the need for manual casting.Correct
Why?

Lightweight generics primarily serve as a compile-time hint for Swift, allowing it to bridge Objective-C collections as type-safe arrays (e.g., [String] instead of [Any]), which eliminates the need for manual casting and improves code safety. Option A is incorrect because the card states that generics do not enforce runtime type checks within Objective-C itself.

Just read this? Test yourself on what you have been reading.

Read the original → developer.apple.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles