私はこのコードを持っ例えば迅速にエラーの使用のまわりで私の頭を取得しようとしている:言葉が悪い場合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'が1つの理由だけで失敗するかもしれないと仮定しています。多くの場合、エラーが発生した可能性があるさまざまな理由があります.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