问题描述
Swift似乎没有C#/ Java类的异常,而是使用断言。但是,这本书说,在生产环境中,他们立即崩溃了应用程序。没有办法吗?单元测试怎么样,如何测试某个函数声明它获得正确的输入值?
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?
推荐答案
从Apple书,Swift编程语言似乎应该使用枚举来处理错误。
From Apple books, The Swift Programming Language it's seems erros should be handle using enum.
这是本书的一个例子。
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)"
}
来自:Apple Inc.Swift编程语言iBooks。
From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/br/jEUH0.l
对于意外的错误,您应该使用NSException作为
For unexpected erros you should use NSException as point out by lfalin
这篇关于有什么办法可以在Swift中得到断言吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!