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

问题描述

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

对于像上述代码,swift二进制抱怨错误不处理,因为封闭函数未声明为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 3:

您不能从计算属性中抛出。如果你想要抛出,你必须使用一个函数。 部分的声明部分Swift编程语言仅将 throws (和 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 2中计算的属性“throws”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 10:20