Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...