如何获取我放入 Error 实例中的字符串?

How to get the string I put into a Error instance?

基本上我明白了,

// MyPackage.swift

enum Error: LocalizedError {
    case general(String)
}

func foobar() throws {
    throw Error.general("haha")
}

do {
    try foobar()
} catch Error.general(let message) {
    // will print "haha"
    print(message)
}

然后在单元测试中,我需要检查我是否得到了完全相同的错误,

import Quick
import Nimble
import MyPackage

class MySpec: QuickSpec {
    
    override func spec() {
        describe("") {
            let input = "haha"
            let count = 2
            let expectation = Error.general("非纯数字字符串无法使用本方法")
            
            context("输入_" + input) {
                it("预期_" + expectation.localizedDescription) {
                    // got the error
                    // but expectation.localizedDescription was not what I looking for
                    expect(try numberStringByAddingZerosInto(input, tillReach: count))
                        .to(throwError(expectation))
                }
            }
        }
    }
}

有效,但是expectation.localizedDescription不是“哈哈”,导致测试用例的名字没有用。 我也试过 expectation.errorDescription 但没有成功。

我在哪里可以得到它? 为什么会这样?

覆盖errorDescription变量

enum Error: LocalizedError {
    case general(String)
    
    var errorDescription: String? {
        switch self {
        case .general(let errorMessage):
            return errorMessage
        }
    }
}

现在你也可以这样写do-catch块了

do {
    try foobar()
} catch let error {
    print(error.localizedDescription)
}