问题描述
是否可以从Objective-C调用Swift协议扩展中定义的方法?
Is it possible to call methods defined in a protocol extension in Swift from Objective-C?
例如:
protocol Product {
var price:Int { get }
var priceString:String { get }
}
extension Product {
var priceString:String {
get {
return "$\(price)"
}
}
}
class IceCream : Product {
var price:Int {
get {
return 2
}
}
}
IceCream
实例的价格字符串为'$ 2',可以在Swift中访问,但是该方法在Objective-C中不可见.编译器将引发错误'IceCream'没有可见的@interface声明选择器...'.
The price string of an instance of IceCream
is '$2' and can be accessed in Swift, however the method is not visible in Objective-C. The compiler throws the error 'No visible @interface for 'IceCream' declares the selector ...'.
在我的配置中,如果直接在Swift对象的实现中定义了该方法,那么一切都会按预期进行.即:
In my configuration, if the method is defined directly in the Swift object's implementation, everything works as expected. i.e.:
protocol Product {
var price:Int { get }
var priceString:String { get }
}
class IceCream : Product {
var price:Int {
get {
return 2
}
}
var priceString:String {
get {
return "$\(price)"
}
}
}
推荐答案
我几乎可以确定答案是否",尽管我还没有找到能说明该问题的Apple官方文档.
I am nearly certain the answer to this is "no", although I haven't found official Apple documentation that spells it out.
这是swift-evolution邮件列表中的一条消息,其中讨论了对所有方法调用使用动态分派的建议,该提议将提供更类似于Objective-C的调用语义:
Here is a message from the swift-evolution mailing list discussing the proposal to use dynamic dispatch for all method calls, which would provide calling semantics more like Objective-C:
协议扩展是仅Swift的语言功能,因此对objc_msgSend()
不可见.
Protocol extensions are a Swift-only language feature, and as such are not visible to objc_msgSend()
.
这篇关于可以在Objective-c中访问的协议扩展上定义Swift方法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!