首先,任何函数都会返回一些东西(至少是一个空元组),即使你没有声明任何返回类型。
(@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, file: StaticString = #file, line: UInt = #line)
@noreturn public func abort()
@noreturn public func exit(_: Int32)
可能还有更多。
(备注:类似的注解存在于其他编程语言中
或编译器,例如 C++11 中的 [[noreturn]],作为 GCC 扩展的 __attribute__((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 返回类型替换了,所以上面的例子
现在应该写成
func myFatalError() -> Never {
// Do something else and then ...
fatalError("Something went wrong!")
}