可以在Objective-c中访问的协议扩展上定义Swift方法吗 [英] Can Swift Method Defined on Extensions on Protocols Accessed in Objective-c

查看:96
本文介绍了可以在Objective-c中访问的协议扩展上定义Swift方法吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

同样,唯一的例外是协议扩展.与语言中的任何其他构造不同,协议扩展方法是在虚拟调度会导致不同结果的情况下静态调度的.没有编译器错误可防止这种不匹配. ( https://lists.swift.org/pipermail/swift-evolution /Week-of-Mon-20151207/001707.html )

协议扩展是仅Swift的语言功能,因此对objc_msgSend()不可见.

Protocol extensions are a Swift-only language feature, and as such are not visible to objc_msgSend().

这篇关于可以在Objective-c中访问的协议扩展上定义Swift方法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆