とrethrows
の違いを理解するための便利で簡単な説明はありませんでした。どのように使用するべきかを理解しようとすると、混乱することがあります。スウィフトのスローとスローフードの違いは何ですか?
私は次のように私は、この種のエラーを伝播するための最も単純な形式での-Default- throws
に精通していますことを言及します:
enum CustomError: Error {
case potato
case tomato
}
func throwCustomError(_ string: String) throws {
if string.lowercased().trimmingCharacters(in: .whitespaces) == "potato" {
throw CustomError.potato
}
if string.lowercased().trimmingCharacters(in: .whitespaces) == "tomato" {
throw CustomError.tomato
}
}
do {
try throwCustomError("potato")
} catch let error as CustomError {
switch error {
case .potato:
print("potatos catched") // potatos catched
case .tomato:
print("tomato catched")
}
}
をこれまでのところは良いが、問題は場合に発生する:
私がこれまで知っているfunc throwCustomError(function:(String) throws ->()) throws {
try function("throws string")
}
func rethrowCustomError(function:(String) throws ->()) rethrows {
try function("rethrows string")
}
rethrowCustomError { string in
print(string) // rethrows string
}
try throwCustomError { string in
print(string) // throws string
}
それはrethrows
とは異なり、try
によって扱われなければならthrows
関数を呼び出すときです。だから何?! throws
またはrethrows
を使用することを決定する際に私たちが従わなければならないロジックは何ですか?スウィフトの本の中で"Declarations"から
偉大な答え。ありがとう。 – Darko
最後の文章は金色です! – Klaas
だから私はそれを要約すると思います。あなたが**常に**投げに制限したいときは '投げる ' – Honey