Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class name is the same as namespace issue

I have an interesting problem involving two different Cocoapods that have a public enum with the same name.

With implicit namespacing this isn't normally a problem except that both Cocoapods have a class that is the same as their target name.

So if I import both Cocoapods in the same file referencing the enum with the same name generates a "enum-name is ambiguous for type lookup in this context", and if I attempt to reference the enum by ModuleName.enum Swift says ModuleName does not have a member named enum.

Presumably this is because the class, and not the namespace doesn't have a member named enum. Anyone know a way around this ?

Here's what this looks like in code:

Cocoapod A:

public enum Test {

}

public class A {

}

Cocoapod B:

public enum Test {

}

public class B {

}

Other file:

import A
import B

// Results in "A does not have a member named Test"
var test: A.Test = A.Test(rawValue: "a")

// Results in "Test is ambiguous for type lookup in this context"
var test: Test = Test(rawValue: "a")
like image 301
Peter Willsey Avatar asked Aug 14 '15 05:08

Peter Willsey


1 Answers

One needs to import the specific type to bring it into your files namespace before other like named types.

I'll use the SwiftMessages framework as an example, there the enum Theme clashes with like named class in another framework.

SwiftMessages also exists as a class within the framework, and Swift always thinks I want to access the class when I type SwiftMessages.Theme.

import enum SwiftMessages.Theme

Now you can use Theme

var theme: Theme

and it will be the expected theme.

If you still have clashes, create a separate source file

// e.g. SwiftMessages+Support.swift
import enum SwiftMessages.Theme

typealias SwiftMessagesTheme = SwiftMessages.Theme

And then use it elsewhere:

var theme: SwiftMessagesTheme
like image 140
emp Avatar answered Oct 06 '22 02:10

emp