Swift显示enum参数的错误消息

时间:2017-05-07 13:38:52

标签: swift error-handling enums

我有这个错误代码枚举

enum EYErrorCode: Error {
    case insufficientFunds(coinsNeeded: Int)
}

我想显示一个类似的错误:

"Error - You need \(coinsNeeded) to perform this action"

但我不知道如何让我的错误显示coinsNeeded参数。

我的代码如下:

static func errorForCode(code: EYErrorCode) -> EYCustomError?
{
        switch code {
          case .insufficientFunds:
            let localizedDescription = NSLocalizedString("You do not have enough cash", comment: "insufficientFunds message")
            return EYCustomError.init(localizedTitle:nil, localizedDescription: localizedDescription, code:code)
        }
}


protocol EYErrorProtocol: Error {
    var localizedTitle: String { get }
    var localizedDescription: String { get }
    var code: Int { get }
}


public struct EYCustomError: EYErrorProtocol {
    var localizedTitle: String
    var localizedDescription: String
    var code: Int

    init(localizedTitle: String?, localizedDescription: String, code: EYErrorCode) {
        self.localizedTitle = localizedTitle ?? "Error"
        self.localizedDescription = localizedDescription
        let err = (code as NSError).code
        self.code = err
    }
}

我的问题:

如何创建显示资金不足(coinsNeeded)参数的错误?

1 个答案:

答案 0 :(得分:3)

对于带参数的枚举,您可以使用switch语句提取相关值,如下所示..

uchar

请参阅Documentation

的关联值部分