基于swift中的字符串值返回枚举类型?

时间:2014-08-22 11:30:15

标签: enums swift

我正在尝试在操场上执行以下操作,以根据字符串分配枚举类型,但在changeType函数中收到错误。我怎样才能让它正常工作?

enum TransactionType {
    case purchase,charge
    case deposit,payment

    func description() -> String {
        switch self {
        case .purchase:
            return "purchase"
        case .charge:
            return "charge"
        case .deposit:
            return "deposit"
        case .payment:
            return "payment"
        }
    }

    func typeFromString(value:String) -> TransactionType   {
        switch value {
        case "charge":
            return .charge
        case "deposit":
            return .deposit
        case "payment":
            return .payment
        default:
            return .purchase
        }
    }
}

class Tester {
    var transactionType = TransactionType.purchase

    func changeType() {
        transactionType = TransactionType.typeFromString("charge")
    }
}

var tester = Tester()
print(tester.transactionType.description())

tester.changeType()
print(tester.transactionType.description())

2 个答案:

答案 0 :(得分:3)

解决方案比你想象的更简单:

enum TransactionType : String {
    case purchase = "purchase", charge = "charge"
    case deposit = "deposit", payment = "payment"
}

class Tester {
    var transactionType = TransactionType.purchase

    func changeType() {
        transactionType = TransactionType.fromRaw("charge")!
    }
}

var tester = Tester()
print(tester.transactionType.toRaw())

tester.changeType()
print(tester.transactionType.toRaw())

诀窍是设置String类型的原始值,它定义与每个枚举案例相关联的类型。

更多信息Raw Values in Enumerations

答案 1 :(得分:1)

您可以将typeFromString方法定义为静态,以避免可选值的并发症。毕竟,它只包含常量。只需在static定义之前添加单词func即可。

static func typeFromString(value:String) -> TransactionType   {