[英]How do I declare that a computed property 'throws' in Swift?
class SomeClass {
var someProperty: Int {
throw Err("SNAFU")
}
}
For code like the above, the swift binary complains 'error is not handled because the enclosing function is not declared 'throws'.对于像上面这样的代码,swift 二进制文件会抱怨“错误未处理,因为封闭函数未声明为“抛出”。
How do I declare that 'someProperty' 'throws' in the above?我如何在上面声明 'someProperty' 'throws'?
class SomeClass {
var someProperty throws: Int {
}
}
and和
class SomeClass {
var someProperty: throws Int {
}
}
and和
class SomeClass {
var someProperty: Int throws {
}
}
don't seem to work.似乎不起作用。
This functionality is added for read-only computed properties in Swift 5.5 as part of SE-0310 (included in Xcode 13).此功能是在 Swift 5.5 中为只读计算属性添加的,作为SE-0310 (包含在 Xcode 13 中)的一部分。
Based on SE-0310, the syntax would be:基于 SE-0310,语法为:
class SomeClass {
var someProperty: Int {
get throws {
throw Err("SNAFU")
}
}
}
Here is the previous answer for versions of Swift prior to 5.5:以下是 5.5 之前的 Swift 版本的先前答案:
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. The Swift Programming Language末尾的 Language Reference部分的声明部分仅列出
throws
(和rethrows
)作为函数和初始化程序声明的关键字。
While it's not possible (yet) to throw
from computed properties in Swift, I found Chris Lattner himself adresses this very same question on one of Apple Developer Forums threads :虽然(还)不可能在 Swift 中从计算属性中
throw
,但我发现Chris Lattner本人在Apple Developer Forums 线程之一上提出了同样的问题:
We agree that you should be able to mark the getters and setters as "throws" in subscripts and computed properties, but haven't gotten there yet.
我们同意您应该能够在下标和计算属性中将 getter 和 setter 标记为“抛出”,但还没有做到这一点。 We are likely to support this at some time, but it isn't clear if it will make it in time for Swift 2.
我们可能会在某个时候支持此功能,但尚不清楚它是否会及时用于 Swift 2。
Let me suggest a workaround: a property can be declared as having type of Result<DesiredPropertyType, Error>
.让我提出一个解决方法:可以将属性声明为具有
Result<DesiredPropertyType, Error>
。 This way it can be accessed like this:这样就可以像这样访问它:
do {
try self.failableProperty.get()
} catch {
...
}
get()
is a built-in method of Swift's Result
. get()
是 Swift 的Result
内置方法。
UPDATE : this is getting addressed in Swift 5.5 with "effectful read-only properties": https://github.com/apple/swift-evolution/blob/main/proposals/0310-effectful-readonly-properties.md .更新:这将在 Swift 5.5 中通过“有效的只读属性”得到解决: https : //github.com/apple/swift-evolution/blob/main/proposals/0310-effectful-readonly-properties.md 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.