objective-c - 可以在 Objective-c 中访问的协议(protocol)的扩展上定义 Swift 方法吗

标签 objective-c swift protocols protocol-extension

是否可以从 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/

相关文章:

c++ - 识别 macOS 当前进程中的堆栈和堆段

ios - Swift:即使我切换到不同的 View Controller ,如何使后台功能保持运行

ios - 在协议(protocol)定义的方法参数中调用的类的前向声明

ios - Xcode 8.1 在尝试启动应用程序时卡住了

ios - 苹果仪器 : Where do <non-object> items come from?

objective-c - 如何将 self 作为方法参数传递?

ios - 当用户拒绝在 Google map 中访问位置时,如何显示用户当前所在的国家/地区?

ios - Swift - 删除带有动态标识符的通知

c++ - 难以理解协议(protocol)定义

ios - swift 中 java 接口(interface)或 objective c 协议(protocol)的等价物是什么?