加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

何时以及如何在Swift中使用@noreturn属性?

发布时间:2020-12-14 05:44:52 所属栏目:百科 来源:网络整理
导读:我在guard-else流的上下文中读取了关键字else之后用大括号括起来的代码块,必须使用return,break,continue或throw调用标有noreturn属性的函数或传递控制. 最后一部分很清楚,虽然我不太了解第一部分. 首先,即使你没有声明任何返回类型,任何函数都会返回一些东
我在guard-else流的上下文中读取了关键字else之后用大括号括起来的代码块,必须使用return,break,continue或throw调用标有noreturn属性的函数或传递控制.

最后一部分很清楚,虽然我不太了解第一部分.

首先,即使你没有声明任何返回类型,任何函数都会返回一些东西(至少是一个空元组).其次,我们什么时候可以使用noreturn函数?文档是否表明某些核心的内置方法标有noreturn?

The else clause of a guard statement is required,and must either call
a function marked with the noreturn attribute or transfer program
control outside the guard statement’s enclosing scope using one of the
following statements:

06000

这是source.

First of all,any function returns something (an empty tuple at least) even if you don’t declare any return type.

(@noreturn已过时;请参阅下面的Swift 3更新.)
不,有一些功能可以立即终止进程
并且不要返回呼叫者.这些都在Swift中标出
与@noreturn,如

@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)

而且可能还有更多.

(注:其他编程语言中也存在类似的注释
或者编译器,例如C [中的[[noreturn]],__ attribute __((noreturn))作为GCC扩展,或_Noreturn为
Clang编译器.)

如果它也终止,你可以使用@noreturn标记自己的函数
无条件地进行该过程,例如通过调用其中一个内置函数,例如

@noreturn func myFatalError() {
    // Do something else and then ...
    fatalError("Something went wrong!")
}

现在,您可以在guard语句的else子句中使用您的函数:

guard let n = Int("1234") else { myFatalError() }

@noreturn函数也可用于标记“不应该”的情况
发生“并指出编程错误.一个简单的例子
(摘自Missing return UITableViewCell):

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属性
已经被Never return类型所取代,所以上面的例子
现在写成

func myFatalError() -> Never  {
    // Do something else and then ...
    fatalError("Something went wrong!")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读