Can objective-c code call swift extension on Class?

百般思念 提交于 2019-11-28 18:04:44

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

All you need to do is:

  • create your extension in Swift (no @objc annotation)

  • import "ProjectTarget-Swift.h" in your ObjectiveC 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];

This solution works for Swift 2.2 and Swift 3. Note that only extensions for classes (not for structs or enums) will be accessible 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.

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

An exception to this is when the category is defined on a bridged type (i.e. the extension is defined on String and not NSString). These categories will not automatically be bridged to their Objective-C counterparts. To get around this, you'll either need to use the Objective-C type (and cast the return value in your Swift code with as String) or define an extension for both the Swift and Objective-C types.

Import "#import "ProductModuleName-Swift.h" header in objective-c file and add @objc infront of your extentsion in swift file. It will working fine in swift 4.2 and swift 5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!