Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

exception - 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'.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This functionality is added for read-only computed properties in Swift 5.5 as part of SE-0310 (included in Xcode 13).

Based on SE-0310, the syntax would be:

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

Here is the previous answer for versions of Swift prior to 5.5:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...