Clicky

iOS Dev Nugget 246 Mapping Swift and Obj-C Method Names

.

Need to run a code review on your codebase? Hire me

If you have been writing Obj-C for a while, you should know that it is a good idea to prefix method names of methods what you define a class extension. eg.

@interface UIViewController (MyViewControllerExtension)

- (void)rsConstraintHeightTo:(CGFloat)height;

@end

Naturally, this gets translated to the following when you call the method in Swift:

rsConstraintHeight(to: 10.0);

What if you wanted to write this:

constraint(height: 10.0);

You can do it by changing your Obj-C declaration to use the NS_SWIFT_NAME macro:

@interface UIViewController (MyViewControllerExtension)

- (void)rsConstraintHeightTo:(CGFloat)height NS_SWIFT_NAME(constraint(height:));

@end

Notice that you can map both the method name and the argument.

Similarly, when you expose a method written in Swift to Obj-C, you can map the method name by including the desired method name with the @objc attribute:

//Instead of just @objc, use:
@objc(rsFoo)
func foo() {}

Then in Obj-C:

[self rsFoo];

This can also be used for mapping enum values from Obj-C to Swift. Refer to the docs under Overriding Swift Names for Objective-C Interfaces for more details.

I picked up this tip from Michel Fortin. Thanks Michel!


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues