class SomeClass {
var someProperty: Int {
throw Err("SNAFU")
}
}
对于像上面这样的代码,swift 二进制文件会提示“没有处理错误,因为封闭函数没有声明为‘throws’”。
如何在上面声明“someProperty”“throws”?
class SomeClass {
var someProperty throws: Int {
}
}
和
class SomeClass {
var someProperty: throws Int {
}
}
和
class SomeClass {
var someProperty: Int throws {
}
}
好像不行。
最佳答案
作为 SE-0310 的一部分,此功能是为 Swift 5.5 中的只读计算属性添加的。 (包含在 Xcode 13 中)。
基于 SE-0310,语法为:
class SomeClass {
var someProperty: Int {
get throws {
throw Err("SNAFU")
}
}
}
这是 5.5 之前的 Swift 版本的先前答案:
您不能从计算属性中抛出。如果你想抛出,你必须使用一个函数。 Declarations section of the Language Reference The Swift Programming Language末尾的部分仅将 throws
(和 rethrows
)列为函数和初始化程序声明的关键字。
关于swift - 如何在 Swift 中声明计算属性 'throws'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899346/