tezvyn:

Exposing Swift classes to Objective-C

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Swift-to-ObjC interop rules.

OUTLINE

subclass NSObject or mark members @objc, import the generated ModuleName-Swift.h, and accept that Swift-only types like enums with associated values cannot cross.

WHAT THIS TESTS It checks whether you understand which direction each interop mechanism serves and what the Objective-C runtime can and cannot represent.

A GOOD ANSWER COVERS To see a Swift API from Objective-C, the class generally must derive from NSObject, and each member you want visible must be exposed to the Objective-C runtime. You do that by marking members @objc, or marking the class @objcMembers to expose all of them, or by inheriting NSObject which makes many members visible. The compiler then emits a header named ModuleName-Swift.h that you #import in your Objective-C source; the Swift symbols appear there with Objective-C-style names. This is distinct from the bridging header, which goes the other way.

LIMITATIONS Only things the Objective-C runtime models can cross the boundary. That excludes Swift generics, structs and enums with associated values, tuples, top-level functions, protocols with associated types or that are not @objc, and many advanced type features. Optionals map to nullable object pointers only; value-type optionals like Int? do not bridge cleanly.

COMMON WRONG ANSWERS Saying the bridging header exposes Swift to Objective-C, which reverses the mechanism. Claiming any Swift type can be exposed with @objc, ignoring the runtime constraints. Forgetting that NSObject inheritance or @objc is required at all.

LIKELY FOLLOW-UPS What happens to a Swift enum with associated values? How are Swift optionals represented in Objective-C? When is @objcMembers preferable to per-member @objc? How does this interact with the Swift name-mangling and the NS_SWIFT_NAME annotations?

ONE CONCRETE EXAMPLE You add a Swift AnalyticsTracker to an Objective-C app. You declare it as class AnalyticsTracker: NSObject and mark log(event:) with @objc. After building, you #import "MyApp-Swift.h" in the legacy view controller and call the tracker directly. An attempt to expose a Result-returning method fails until you refactor it to a completion handler the runtime can model.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.