2

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?

Łukasz
  • 773
  • 5
  • 23
  • So in that file, you are using things from both modules, but are also trying to use `CGPoint.+`? Are they implemented in the same way? Or are you trying to use a specific module's implementation? – Sweeper Nov 13 '22 at 12:16
  • In one of them labels are different `static func + (left: CGPoint, right: CGPoint)`. Expected result is the same. – Łukasz Nov 13 '22 at 12:34

1 Answers1

3

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)

Sweeper
  • 213,210
  • 22
  • 193
  • 313