我试图让我在周围迅速例如使用错误的头我有这样的代码:如果字是坏Error,throws和catch的用法是什么?
import UIKit
class ViewController: UIViewController {
enum SomeError: Error
{
case badWord
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
do {
try checkWord()
}
catch SomeError.badWord {
print("error!")
}
catch { //This is like a defualt statement
print("Something weird happened")
}
}
func checkWord() throws {
let word = "crap"
guard word != "crap" else {
throw SomeError.badWord
}
print("Continuing the function")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
的checkWord
功能将终止。然而,同样的行为可以通过以下方式实现:
func checkWord() {
let word = "crap"
guard word != "crap" else {
print("error!")
return
}
print("Continuing the function")
}
那么定义错误和通过catch语句的用法是什么?
好处是您调用该功能的网站。 'JSONSerialization'库就是一个很好的例子。如果您传递的数据不是有效的JSON,则会引发错误。在Objective-C中,你会传递一个错误指针给方法,然后检查它是否有错误。在Swift中,该方法要么返回正确的结果,要么在失败时引发错误。 – daltonclaybrook
你也假设'checkWord'可能会因为一个原因失败。通常,您可能有多种原因可能会引发错误,正如Martin所说,调用例程可能想根据错误类型采取不同的操作。请参阅[Swift编程语言:错误处理](https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42 -ID508)为更丰富的例子。 – Rob