How do I declare that a computed property 'throws' in Swift?

math4tots picture math4tots · Oct 2, 2015 · Viewed 12.9k times · Source
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'.

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

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.

Answer

Charles A. picture Charles A. · Oct 2, 2015

Update for Swift 5: This is still not possible.

As of Swift 3:

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.