我最近尝试运行此代码
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 '()'
这个函数不应该返回原始字符串吗?难道我做错了什么?请帮助。
答案 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
}
}