简体   繁体   中英

Swift Enum with multiple types

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

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)")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM