How can I call Swift extension method in my Objective-C class?It doesn't work when using @objc.

I need call Swift extension method in Objective-C method. But it remind me "No visible @interface for 'XXX' declares the selector 'custom-extension-method'". What should I do for the Swift extension method?
Answered by OOPer in 674851022
NSData is automatically bridged to Data in Swift, but it does not mean extension for Data is available in NSData.

You may need another extension for NSData, something like:
Code Block
extension NSData {
@objc func AES128Encrypt() throws -> Data {
return try (self as Data).AES128Encrypt()
}
}


And you need to know how Swift methods with throws are converted to Objective-C:
Code Block
#import "YourModuleName-Swift.h"
//...
NSError *error = nil;
NSData *encryptedData = [resultData AES128EncryptAndReturnError:&error];
//...


What should I do for the Swift extension method?

You should better show what you have done till now.
Can you show all the relevant codes?
OK. Thanks for your help. @OOPer

In Swift code, there is AESEncrypt method extension for Data in Data+AES.swift class.
Code Block
extension Data {
   
  func AES128Encrypt() throws -> Data {
......
}

In Objective-C code, I need to call the AESEncrypt method for resultData. But resultData cannot call the AES128Encrypt method.
Code Block
NSData *aesEncryptData = [resultData AES128Encrypt];

When I add @objc in swift extension method, It's showing "@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes".

Accepted Answer
NSData is automatically bridged to Data in Swift, but it does not mean extension for Data is available in NSData.

You may need another extension for NSData, something like:
Code Block
extension NSData {
@objc func AES128Encrypt() throws -> Data {
return try (self as Data).AES128Encrypt()
}
}


And you need to know how Swift methods with throws are converted to Objective-C:
Code Block
#import "YourModuleName-Swift.h"
//...
NSError *error = nil;
NSData *encryptedData = [resultData AES128EncryptAndReturnError:&error];
//...


  • - NSData is automatically bridged to Data in Swift, but it does not mean extension for Data is available in NSData.

that is the truth.

I will try it and thank you for help.
How can I call Swift extension method in my Objective-C class?It doesn't work when using @objc.
 
 
Q