It seems that Swift doesn't have C#/Java-like exceptions and uses assertions instead. However, the book says that in production environment, they instantly crash the app. Isn't there a way around it? What about unit tests, how can I test that a certain function asserts that it gets a correct input value?
问题:
回答1:
From Apple books, The Swift Programming Language it's seems erros should be handle using enum.
Here is an example from the book.
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
switch success {
case let .Result(sunrise, sunset):
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
let serverResponse = "Failure... \(error)"
}
From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/br/jEUH0.l
For unexpected erros you should use NSException as point out by lfalin
回答2:
As you mentioned, assertions will crash your app in debug or production. They aren't designed to function like Java/C# exceptions. Their only real purpose is:
Use an assertion whenever a condition has the potential to be false, but must definitely be true in order for your code to continue execution. ... in situations where invalid conditions are possible, an assertion is an effective way to ensure that such conditions are highlighted and noticed during development, before your app is published.
Since you can use Cocoa classes in Swift, you're still able to use NSException
for exceptional things that your code can handle.
回答3:
You can add try-catch support for Swift by following the instructions in this article: https://medium.com/@_willfalcon/adding-try-catch-to-swift-71ab27bcb5b8
Basically, it's a wrapper around Obj-C try-catch