Can objective-c code call swift extension on Class?

sprhawk picture sprhawk · Nov 24, 2014 · Viewed 52.3k times · Source

I searched some posts, I think I cannot write an extension under swift, and call it from Objective-C code, right ?

@objc like attributes only support methods, class, protocols ?

Answer

marius bardan picture marius bardan · Feb 4, 2015

You can write a Swift extension and use it in Objective-C code. Tested with XCode 6.1.1.

All you need to do is:

  • create your extension in Swift (@objc annotation needed since Swift 4.0.3)

  • #import "ProjectTarget-Swift.h" in your Objective-C class (where "ProjectTarget" represents the XCode target the Swift extension is associated with)

  • call the methods from the Swift extension