Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Objective-C code call Swift class extensions?

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 ?

like image 299
sprhawk Avatar asked Nov 24 '14 04:11

sprhawk


People also ask

Can Objective-C class inherit from Swift class?

When writing Swift code, some language constructs can be seen in the OBJC runtime automatically and with Swift 3.1 that support is provided automatically. Swift classes that are inherited from OBJC classes are bridged automatically.

Does Objective-C have extensions?

Instead, Objective-C allows you to add your own methods to existing classes through categories and class extensions.

How do I add Swift to Objective-C project?

To access and use swift classes or libraries in objective-c files start with an objective-c project that already contains some files. Add a new Swift file to the project. In the menu select File>New>File… then select Swift File, instead of Cocoa Touch Class. Name the file and hit create.

Is Swift interoperable with Objective-C?

Having access to those runtimes makes the interoperability between Swift and Objective-C easier to bridge. Because Swift already has access to Objective-C and because Swift can expose methods to the Objective-C runtime, there is no problem having a project that contains code in both languages.


2 Answers

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

like image 135
marius bardan Avatar answered Sep 20 '22 14:09

marius bardan


I found out that in Swift 4.0 I had to add @objc in front of my extension keyword in order for the Swift extension methods to become visible by an instance of the Objc class I was extending.

In short:

File configuration setup:

CustomClass.h CustomClass.m CustomClassExtension.swift 

In CustomClassExtension:

@objc extension CustomClass {     func method1()      {         ...     } } 

In my AppDelegate.m:

self.customClass = [[CustomClass alloc] init]; [self.customClass method1]; 
like image 45
ReyAndRey Avatar answered Sep 23 '22 14:09

ReyAndRey