如何声明Swift中的计算属性“抛出”? [英] How do I declare that a computed property 'throws' in Swift?

查看:69
本文介绍了如何声明Swift中的计算属性“抛出”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class SomeClass {
  var someProperty: Int {
    throw Err("SNAFU")
  }
}

对于上述代码,快速二进制文件抱怨未处理错误,因为未将包围函数声明为 throws。

For code like the above, the swift binary complains 'error is not handled because the enclosing function is not declared 'throws'.

如何在上面声明 someProperty为 throws?

How do I declare that 'someProperty' 'throws' in the above?

class SomeClass {
  var someProperty throws: Int {
  }
}

class SomeClass {
  var someProperty: throws Int {
  }
}

class SomeClass {
  var someProperty: Int throws {
  }
}

似乎不起作用。

推荐答案

Swift 5的更新:仍然如此

Update for Swift 5: This is still not possible.

从Swift 3开始:

As of Swift 3:

您不能从计算属性中抛出。如果要抛出,必须使用一个函数。 末尾的语言参考的声明部分 Swift编程语言仅将抛出(和 rethrows )列为函数和初始化程序声明的关键字。

You cannot throw from a computed property. You must use a function if you want to throw. The Declarations section of the Language Reference part at the end of The Swift Programming Language only lists throws (and rethrows) as a keyword for function and initializer declarations.

这篇关于如何声明Swift中的计算属性“抛出”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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