Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name collisions for extension methods from different frameworks

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
}

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?

like image 502
Boon Avatar asked Nov 24 '15 11:11

Boon


People also ask

What is extension method in VB net?

Extension methods enable developers to add custom functionality to data types that are already defined without creating a new derived type. Extension methods make it possible to write a method that can be called as if it were an instance method of the existing type.

Are extension methods good?

Adding extension methods to any type is a great way to improve productivity and simplify code.

What is an extension in Swift?

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you don't have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C.


2 Answers

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

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.

screenshot

like image 130
rintaro Avatar answered Oct 18 '22 12:10

rintaro


After doing a bit of experimentation, the only way I've found is to only import one of the frameworks into your source file.

like image 20
JeremyP Avatar answered Oct 18 '22 13:10

JeremyP