Swift Proposal: Objective-C Implementations in Swift

submited by
Style Pass
2024-05-11 13:30:06

Swift has always had a mechanism that allows Objective-C code to use Swift types: the @objc attribute. When a class is marked with @objc (or, more typically, inherits from an @objc or imported Objective-C class), Swift generates sufficient Objective-C metadata to allow it to be used through the Objective-C runtime, and prints a translated Objective-C declaration into a generated header file that can be imported into Objective-C code. The same goes for members of the class.

This feature works really well for mixed-language apps and project-internal frameworks, but it’s poorly suited to exposing private and especially public APIs to Objective-C.

We propose adding a new attribute, @implementation, which, when paired with an interop attribute like @objc, tells Swift that it is to implement a declaration it has imported from another language, rather than creating a new declaration and exporting it to that language.

Specifically, in this proposal, @objc @implementation allows a Swift extension to replace an Objective-C @implementation block. You write headers as normal for an Objective-C class, but instead of writing an @implementation in an Objective-C file, you write an @objc @implementation extension in a Swift file. You can even port an existing class’s implementation to Swift one category at a time without breaking backwards compatibility.

Leave a Comment