有没有办法覆盖守卫声明?

时间:2017-09-08 06:38:13

标签: ios iphone swift

我知道它看起来不可能也可能会得到负面的标记,但我仍然想知道我们是否可以做一些事情来覆盖guard语句,以便我们可以在调用guard语句时获取方法调用。 例如 -

guard let string = testString else {
    BuggerManager.send(exType: .invalidArgumentException, exMessage: "testString is nil")
    return
}
print(string)

// it happened very rare
@IBAction func toErrorDivideHandled() {
    do {
        let some = try self.divide(x: 10, y: 0)
        print(some)
    } catch let error {
        BuggerManager.send(exType: .decimalNumberDivideByZeroException, exMessage: error.localizedDescription)
    }
}

OR

我们可以创建全局防护类型方法吗?如果是,那么我们如何创造呢。提前致谢。我希望你明白我的观点。

1 个答案:

答案 0 :(得分:1)

你不能覆盖guard语句,但你可以通过包装它并使用Swift的错误处理机制来近似你想要做的事情:

enum GuardError: Error {
    // In practice, put arguments on this case
    // that you use to describe the error
    case doesntExist
}

func guardIt<T>(_ closure: () -> T?) throws -> T {
    guard let ret = closure() else { throw GuardError.doesntExist }
    return ret
}

然后您可以这样使用:

let foo = try guardIt { somePossiblyNilThing }

catch区块中,您可以使用枚举案例中的参数将相应的信息发送到BuggerManager