简体   繁体   中英

How to call a swift method which parameter is a protocol from Objective C

How to call a swift method which parameter is a protocol from Objective C.

Class A
{
func sendMessage<Serializable: Encodable>(message:Serializable){
        let jsonData =   try! JSONEncoder().encode(message)

    }
}

Objecive C code

A a = [[A alloc] init];
[a sendMessage] ;// Not Available

How can I call this method from Objective C.

I don't think sendMessage will ever appear in compiled TargetName-Swift.h because Generics and Encodable protocol is not available in Objective-C .

Clearly when you use

sendMessage<Serializable: Encodable>(message:Serializable)

You employ Generics as well as Encodable protocol which is only available in Swift not in Objective-C

When you try to access the Swift functions in your Objective-C files, compiler creates a Objective-C equivalent/ counterpart of your Swift functions hence you see the signature for those methods in your TargetName-Swift.h files.

But Generics and Encodable protocol are not available in Objective-C so it can't translate your Swift function using Generics and Encodable protocol to Objective-C equivalent. Hence You can never call such Swift methods from Objective-C files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM