Can objective-c code quick call for class quick call?

I was looking for some posts, I think I can not write the extension under swift and call it Objective-C code, right?

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

+47
objective-c swift swift-extensions
Nov 24 '14 at 4:04
source share
4 answers

You can write a Swift extension and use it in ObjectiveC code. Tested with Xcode 6.1.1.

All you have to do is:

  • create extension in Swift (@objc annotation)

  • import "ProjectTarget-Swift.h" into your ObjectiveC class (where "ProjectTarget" represents the Xcode target that the Swift extension is associated with)

  • call methods from the Swift extension

+45
Feb 04 '15 at 12:09
source share

This solution works for Swift 2.2 and Swift 3 . Note that only extensions for classes (not structures or enumerations) will be available from Objective-C.

import UIKit extension UIColor { //Custom colours class func otheEventColor() -> UIColor { return UIColor(red:0.525, green:0.49, blue:0.929, alpha:1) } } 

Then #import "ProductModuleName-Swift.h" in your ObjC file.

+35
Aug 28 '15 at 16:45
source share

As described in other answers, importing the generated Swift header works in most cases .

The exception is that the category is defined by the bridge type (i.e., the extension is defined by String , not NSString ). These categories will not automatically connect to their Objective-C partners. To get around this, you will need to use the Objective-C type (and enter the return value in the Swift code using as String ) or specify an extension for the Swift and Objective-C types.

+33
Feb 29 '16 at 16:57
source share

I found out that in Swift 4.0 I had to add @objc before my extension so that the Swift extension methods became visible as an instance of the Objc class I expanded.

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]; 
+10
Oct 23 '17 at 20:09 on
source share



All Articles