简体   繁体   English

多种类型的Swift Enum

[英]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. 我试图弄清楚如何将Java枚举复制到Swift中,我不知道这是否是正确的方法。

My Enum in Java which i am trying to write in Swift: 我想用Swift编写的Java枚举:

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: 我的Swift代码:

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. 不幸的是,这样我可以在每个枚举上调用方法getName()和getNumber(),这很糟糕,因为我希望根据枚举类型来呈现这些方法。 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. 绝对可以有一个带有不同类型关联值的enum ,我认为这可以为您提供所需的内容。 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)")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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