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 ?
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.
Instead, Objective-C allows you to add your own methods to existing classes through categories and class extensions.
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.
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.
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
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With