How to avoid import function from Module

434 views Asked by At

I have two Packages: FirstModule and AnotherModule, and each of them defines

extension CGPoint {
    public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        CGPoint(x: lhs.x + rhs.x, y: lhs.y+rhs.y)
    }
}

Also in main app I defined

extension CGPoint {
#if !canImport(FirstModule) && !canImport(AnotherModule)
    public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
        CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
    }
...
#endif
}

and some class in another file:

#import FirstModule 
#import AnotherModule

class Whatever() {
    ///Uses CGPoint + CGPoint
}

Unfortunately, compiler throws an error: Ambiguous use of operator '+' and point on both imported modules. Not all classes in my app use FirstModule and AnotherModule but they need just func + ()

How to avoid import func + () from FirstModule and AnotherModule in Whatever class?

1

There are 1 answers

0
Sweeper On BEST ANSWER

One potential way to do this is to explicitly import everything you are using from one of the modules.

You can explicitly import typealiases, structs, classes, enums, protocols, global lets, vars and functions.

Example:

import typealias FirstModule.SomeTypeAlias
import struct FirstModule.SomeStruct
import class FirstModule.SomeClass
import enum FirstModule.SomeEnum
import protocol FirstModule.SomeProtocol
import let FirstModule.someGlobalConstant
import var FirstModule.someGlobalVar
import func FirstModule.someGlobalFunction
import AnotherModule

// now you will use the CGPoint.+ from AnotherModule

Note that you cannot explicitly import extensions or operators. If you need extensions or operators (that are not CGPoint.+) from FirstModule, I would suggest that you move those to another file with only import FirstModule.

(Needless to say, you should replace FirstModule with the module from which you are using fewer members)