Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Swift protocols be defined as dynamic?

I've converted most of my application to Swift. What's left is a number of Objective-C protocols, and some code that should use Swift idioms in place of Objective-C style.

I've done the assembly of my application using Typhoon. Now after converting one of the protocols to Swift, I noticed the intializer was no longer dynamic (required by the DI library). So I tried marking it explicitly dynamic, but got the following error:

Protocol can't be dynamic

Its complaining that the 3rd argument (my Swift protocol) can never participate as part of Objective-C. This seems like it would be a widespread limitation for Swift/ObjC interoperability. Is the only solution to define the protocol in ObjC and have the Swift classes implement that?

The following solution did not work:

public protocol WeatherReportDao : NSObjectProtocol { //Extend NSObjectProtocol 
}
like image 466
Jasper Blues Avatar asked Nov 27 '25 04:11

Jasper Blues


1 Answers

It seems that the best work-around is to add the @objc directive to the Swift protocol. Example:

@objc public protocol CityDao {

//etc. . . 

}

. . to me, this is archaic, as what I'd really like to communicate is that the protocol requires dyanmic dispatch - something that can go beyond Swift-ObjC interoperability.

Still, it works just fine.

like image 71
Jasper Blues Avatar answered Nov 29 '25 22:11

Jasper Blues