何时以及如何在Swift中使用@noreturn属性?
我在guard-else流的上下文中读取了关键字else之后用大括号括起来的代码块,必须使用return,break,continue或throw调用标有noreturn属性的函数或传递控制.
最后一部分很清楚,虽然我不太了解第一部分. 首先,即使你没有声明任何返回类型,任何函数都会返回一些东西(至少是一个空元组).其次,我们什么时候可以使用noreturn函数?文档是否表明某些核心的内置方法标有noreturn?
这是source.
(@noreturn已过时;请参阅下面的Swift 3更新.) @noreturn public func fatalError(@autoclosure message: () -> String = default,file: StaticString = #file,line: UInt = #line) @noreturn public func preconditionFailure(@autoclosure message: () -> String = default,line: UInt = #line) @noreturn public func abort() @noreturn public func exit(_: Int32) 而且可能还有更多. (注:其他编程语言中也存在类似的注释 如果它也终止,你可以使用@noreturn标记自己的函数 @noreturn func myFatalError() { // Do something else and then ... fatalError("Something went wrong!") } 现在,您可以在guard语句的else子句中使用您的函数: guard let n = Int("1234") else { myFatalError() } @noreturn函数也可用于标记“不应该”的情况 override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: MyTableViewCell switch (indexPath.row) { case 0: cell = tableView.dequeueReusableCellWithIdentifier("cell0",forIndexPath: indexPath) as! MyTableViewCell cell.backgroundColor = UIColor.greenColor() case 1: cell = tableView.dequeueReusableCellWithIdentifier("cell1",forIndexPath: indexPath) as! MyTableViewCell cell.backgroundColor = UIColor.redColor() default: myFatalError() } // Setup other cell properties ... return cell } 没有myFatalError()标记为@noreturn,编译器会 更新:在Swift 3(Xcode 8 beta 6)中的@noreturn属性 func myFatalError() -> Never { // Do something else and then ... fatalError("Something went wrong!") } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |