Can I restrict the type that a function throws in Swift?

懵懂的女人 提交于 2019-12-18 14:52:47

问题


When calling a function in Swift 3 that throws, you have to be exhaustive in catching all possible errors, which often means you have an unnecessary extra catch {} at the end to handle errors that won't happen.

Is it possible to say throws MyErrorType so that the compiler can know you have indeed been exhaustive when you handle all cases from that enumeration?


回答1:


There's no simple way to be type-safe with thrown errors. Consider this, if the compiler allowed you to specify throws MyErrorType, then it would also have to ensure within that function body that you're not trying a function that could potentially throw a different type outside of a do/catch block. (Well there is but it would add layers of unnecessary complexity). The Swift compiler can already be slow and get stuck in loops when inferring types, inferring Thrown types all the way up a chain of throwing functions could be a nightmare.

The running idea is that for most errors you're going to handle them in a small subset of ways anyhow.

That being said, there's no need for you to add extra catch let error as MyErrorType clauses, you can simply use a switch in a catch block like so:

do {
  try something()
} catch let e {
  switch e {
  case let m as MyErrorType: handleMyError(m)
  case let o as OtherErrorType: handleOther(o)
  case is ThirdErrorType: print("error \(e)")
  default: handleElse(e)
  }
}


来源:https://stackoverflow.com/questions/39618095/can-i-restrict-the-type-that-a-function-throws-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!