Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Enum with multiple types

Tags:

swift

I am trying to figure out how to duplicate my Java Enum into Swift and i don't know if this is the right way.

My Enum in Java which i am trying to write in Swift:

public enum EnumDB {

    DATABASE_NAME("DataBase"),
    DATABASE_VERSION(1);

    private String name;
    private int value;

    private EnumDB(String name) {
        this.name = name;
    }

    private EnumDB(int value) {
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public int getValue() {
        return value;
    }

}

My Swift Code:

enum EnumDB {

    case Name,Version

    func getName() -> String{
        switch self{
        case .Name: return "DataBase"
        }
    }

    func getNumber() -> Int{
        switch self{
        case .Version: return 1
        default: return 0
        }
    }
}

My questions are:

  1. Is this the right way to create an Enum with multiple value types , each enum contains a different type?
  2. unfortunately this way i can call the methods getName() and getNumber() on each Enum which is bad because i would want those methods to be presented according to the enum type. Enum Associative values and Raw Values didn't help to conclusion what i am looking for is writing an enum that his values can contains different types.

thanks

like image 558
Jotta E Avatar asked Oct 28 '25 09:10

Jotta E


1 Answers

You can definitely have an enum with associated values of different types, which I think can give you what you're looking for. This is how I might implement your example:

enum EnumDB {
    case Name(String)
    case Version(Int)
}

let namedDB = EnumDB.Name("databaseName")

switch namedDB {
case .Name(let name):
    println("Database name is \(name)")
case .Version(let versionNumber):
    println("Database version is \(versionNumber)")
}
like image 140
Nate Cook Avatar answered Oct 30 '25 11:10

Nate Cook