swift - 如何在 Swift 中声明计算属性 'throws'?

标签 swift exception swift2

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/

相关文章:

ios - 如何对从服务器接收响应的代码进行单元测试

c# - 子字符串 StringBuilder c#

ios - fatal error : init(coder:) has not been implemented Xcode 7 iOS 9

Swift:如何检查 AnyObject 是否为零?

ios - 无法快速使用 FMDB 加载数据库

ios - 核心数据删除只能间歇性工作

exception - 缓存未命中是一种中断/故障吗

python - 自定义异常的列表。如何创建这样的列表?

iOS UILocalNotification 已计划,但未触发

macos - 屏幕中央窗口