我有抛出错误的错误吗?我该怎么办?

时间:2019-11-02 20:56:07

标签: swift error-handling switch-statement

我最近尝试运行此代码

extension String: Error {} //string isn't throw-able by default 

func throwingFunction() throws { //this function always throws on call. So far so good
    throw "error"
}

switch try throwingFunction() {
    case "error": print("It works!") //but it doesn't 
    default: break
}

错误为expression pattern of type 'String' cannot match values of type '()' 这个函数不应该返回原始字符串吗?难道我做错了什么?请帮助。

1 个答案:

答案 0 :(得分:0)

throwingFunction()如果未引发错误,则返回Void()。 您无法打开Void

因此,您需要try才能执行功能并捕获error,然后才能打开error本身。

do {
    try throwingFunction()
} catch {
    switch error as! String { // Since you know the error type, It's perfectly safe to force unwrap
    case "error": print("It works!")
    default: break
    }
}