抛出未包装的nil可选项

4

考虑以下代码:

enum MyErrorType:ErrorType {
    case BadTimes
}

var mightHaveAValue: String?

do {

    if let value = mightHaveAValue {
        // do stuff with value
    } else {
        throw MyErrorType.BadTimes
    }

    // do stuff with NSFileManager using mightHaveAValue which might throw

} catch {
    // handle error
}

我有一个很大的do/try/catch代码块,与此同时无论 mightHaveAValue 是否为空或稍后对 NSFileManager 造成了错误,错误处理将是相同的。因此,重复使用错误处理代码是有意义的。

在Swift2中,这是最干净的方法吗?还是说有一种方式可以自动抛出/捕获没有值的可选项解包异常?

2个回答

9

看起来不错,但是使用 guard let 要比使用 if let 更好,因为它可以让你在主要的 do 块中使用解包后的值,而不是必须在一个 if let 分支内工作。你也可以使用多个 catch 分支来处理不同的错误类型。

do {

    guard let value = mightHaveAValue else {
        throw MyErrorType.BadTimes
    }

    // do stuff with value

} catch let error as MyErrorType {
    // handle custom error
} catch let error as NSError {
    // handle generic NSError
}

没有自动处理可选项的方法,您必须使用众多已知的方式之一进行处理: if let, guard let, nil coalescing等。


谢谢 - 出于某种原因,我错误地认为 guard let 只能在函数顶部使用,只因为所有示例用例似乎都是如此。 - Andrew Ebling

7

也许只需使用这样的扩展程序

extension Optional {

    func throwing() throws -> Wrapped {
        if let wrapped = self {
            return wrapped
        } else {
            throw NSError("Trying to access non existing value")
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接