我試圖讓我在周圍迅速例如使用錯誤的頭我有這樣的代碼:如果字是壞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