是否可以从 Objective-C 调用 Swift 协议(protocol)扩展中定义的方法?
例如:
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 中不可见。编译器抛出错误“No visible @interface for 'IceCream' declares the selector ...”。
在我的配置中,如果该方法是直接在 Swift 对象的实现中定义的,那么一切都会按预期进行。即:
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 官方文档。
这是一条来自 swift-evolution 邮件列表的消息,讨论了对所有方法调用使用动态分派(dispatch)的提议,这将提供更像 Objective-C 的调用语义:
Again, the sole exception to this is protocol extensions. Unlike any other construct in the language, protocol extension methods are dispatched statically in a situation where a virtual dispatch would cause different results. No compiler error prevents this mismatch. (https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151207/001707.html)
协议(protocol)扩展是 Swift 独有的语言特性,因此对于 objc_msgSend()
是不可见的。
关于objective-c - 可以在 Objective-c 中访问的协议(protocol)的扩展上定义 Swift 方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762841/