How to make your code more Swifty using NS_SWIFT_NAME

NS_SWIFT_NAME is an attribute in Objective-C that is used to specify a Swift-compatible name for an Objective-C symbol.

When writing Objective-C code that needs to be accessed from Swift, it is often necessary to provide alternate names for Objective-C symbols that have names that do not conform to Swift’s naming conventions. For example, in Objective-C, it is common to prefix method names with a two-letter code that indicates the class the method belongs to (e.g., UIView addSubview:). However, in Swift, this prefix is not used, and the method would be accessed as addSubview(_:).

To provide a Swift-compatible name for an Objective-C symbol, you can use the NS_SWIFT_NAME attribute. Here’s an example:

@interface MyClass : NSObject

- (void)doSomething;


@implementation MyClass

- (void)doSomething NS_SWIFT_NAME(myDoSomething()) {
    // Implementation


In this example, the doSomething method is given the Swift-compatible name myDoSomething() using the NS_SWIFT_NAME attribute. This means that in Swift code, the method would be accessed as myDoSomething().

Leave a Reply

Your email address will not be published. Required fields are marked *