Home > Software design >  Namespace in Swift: Differentiate between an enum and a class
Namespace in Swift: Differentiate between an enum and a class

Time:02-20

I'm importing a framework called Fruits into my class. Fruits has an Enum FruitType which contains case Banana. The Fruits framework also contains a class Banana. Both are public.

enum FruitType {
 case Banana
}

class Banana {
   func eat() -> Bool { ... }

}

My current class

import Fruits

class ClassA {
      function1() { (banana: Fruits.Banana) in {
          return banana.eat()
        }
      }
      
      func function1<T>(funcparam: (T) -> Bool) {  } 


} 

The exact details of the function aren't important, but I'm getting an error saying Banana the enum doesn't have the function eat(). How do I differentiate between the enum and the class, while also importing both because I need them both in different places. I need the whole module to be imported too so I can access a lot of other things, so I can't just do

import enum Fruits.FruitType
import class Fruits.Banana

Though I know this would solve the specific example, I would like to also import the rest of Fruits.

CodePudding user response:

It turns out you can make a file that has a typealias

import class Fruits.Banana

typealias BananaClass = Fruits.Banana

Then just use BananaClass instead in ClassA

CodePudding user response:

I suggest to follow the Swift standard in terms of lower and upper cased names:

  • your class should be Banana (upper case B)
  • your enum case should be banana (lower case b)

This will help to avoid misinterpretations and it might help the compiler.

  • Related