有什么办法可以在Swift中得到断言吗? [英] Is there any way I can catch assertions in Swift?

查看:130
本文介绍了有什么办法可以在Swift中得到断言吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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。 https://itun.es/br/jEUH0.l

From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/br/jEUH0.l

对于意外的错误,您应该使用NSException作为 lfalin

For unexpected erros you should use NSException as point out by lfalin

这篇关于有什么办法可以在Swift中得到断言吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆