如何在swift中只使用数字作为可接受字符串来创建枚举



我想在swift中创建一个只有数字(即"0".."9"(作为可接受值的枚举。

public enum Digit: String {
case "1"
case "2"
case "3"
case "4"
case "5"
case "6"
case "7"
case "8"
case "9"
case "0"
}

但我得到编译错误说Consecutive declarations on a line must be separated by ';'。我试着做

public enum Digit: String {
case 1
}

但这也不起作用。

枚举事例不能是原始类型,即String("1"(或Int(1(。您需要按如下方式添加案例。

public enum Digit: String {
case one = "1"
case two = "2"
//...
}

尽管您可以为Int添加自定义init,如下所示。

public enum Digit: String {
//...
init?(rawValue: Int) {
switch rawValue {
case 1: self == one
case 2: self == two
//...
}
}

最新更新