命名来自不同框架的扩展方法的冲突 [英] Name collisions for extension methods from different frameworks

查看:372
本文介绍了命名来自不同框架的扩展方法的冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为测试,我创建了两个框架。两个框架都包含此扩展名:

As a test, I created two frameworks. Both frameworks contain this extension:

public extension UIDevice {
    var extraInfo: UIDeviceExtraInfo {
        return UIDeviceExtraInfo()
    }
}

public class UIDeviceExtraInfo {
    public var prop: String = "Device1"  //"Device2" is used in another framework
}

然后我导入了两个框架并尝试打印 UIDevice.currentDevice( ).extraInfo.prop 。 Swift编译器给出错误:不明确地使用extraInfo

I then imported the two frameworks and attempt to print UIDevice.currentDevice().extraInfo.prop. Swift compiler gives the error: Ambiguous use of extraInfo".

如何解决名称冲突这样的问题?

How does one go about resolving name clashing like this?

推荐答案

在这种特定情况下,您可以消除 extraInfo prop的歧义explicilty指定预期类型:

In this specific case, you can disambiguate extraInfo prop by explicilty specifying expected type:

import FW1
import FW2

let fw1Info = UIDevice.currentDevice().extraInfo as FW1.UIDeviceExtraInfo
let fw2Info = UIDevice.currentDevice().extraInfo as FW2.UIDeviceExtraInfo
print(fw1Info.prop) // -> Device1
print(fw2Info.prop) // -> Device2

但是,当方法/ prop返回相同类型时:

But, when the method/prop return the same type:

// FW1
public extension UIDevice {
    var myInfo: String { return "Device1" }
}

// FW2
public extension UIDevice {
    var myInfo: String { return "Device2" }
}

// App
import FW1

print(UIDevice.currentDevice().myInfo) // -> ???

无法消除歧义。并且无论应用程序代码导入哪个框架,似乎,实际调用的实现都取决于先到先得方式中链接框架和库中的顺序。但是,据我所知,这种行为无法保证。

There is no way to disambiguate them. And regardless the application code imports which Framework, it seems, the actual called implementation depends on the order in Linked Frameworks and Libraries in "First come, first served" manner. But, as far as I know, this behavior is not guaranteed.

这篇关于命名来自不同框架的扩展方法的冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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