Name collisions for extension methods from different frameworks

前端 未结 3 1132
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 06:36

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

public extension UIDevice {
    var extraInfo: UIDeviceExtraInfo {
        return U         


        
相关标签:
3条回答
  • 2021-02-04 07:07

    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.

    0 讨论(0)
  • 2021-02-04 07:11

    Found this on a project where I have CryptoSwift and after that I was already "compiled" a propietary framework without source code only header files.

    So in this moment you have 3 options:

    1. Ask the providers to change their names
    2. Modify one of them (in this case crypto swift because it is open source and you can modify the name of the extensions, obviously not only in your code that calls it, but in the cloned dependency... which is a hasle if you need to upgrade dependencies)
    3. Change the name you call it so there is no error and know the internal you want to use, I did make an extension in this case of Data and copied what CryptoSwift did to my own file where the collision existed (so it take a local definition of the code):
    extension Data {
        public var myBytes: Array<UInt8> {
            return Array(self)
        }
    }
    

    See that now I have to change all the calls of my code to myBytes and that I have the source code to implement this call, so no more collisions even if you cant do 1 or 2 (because to much hasle). If you cant do any of the 3, I guess there is no solution.

    BY the way, it is unfortunate that swift doesn't support a way to disambiguate this on the language itself.

    0 讨论(0)
  • 2021-02-04 07:15

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

    0 讨论(0)
提交回复
热议问题