我可以限制函数在Swift中抛出的类型吗? [英] Can I restrict the type that a function throws in Swift?

查看:82
本文介绍了我可以限制函数在Swift中抛出的类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 3中调用函数throws时,您必须穷举捕获所有可能的错误,这通常意味着您最后没有多余的catch {}来处理不会发生的错误./p>

是否可以说throws MyErrorType,以便编译器在处理该枚举中的所有情况时都知道您确实已经穷尽了?

解决方案

没有简单的方法可以在引发错误的情况下进行类型安全.考虑到这一点,如果编译器允许您指定throws MyErrorType,那么它还必须确保在该函数体内没有try一个可能在do/catch块之外抛出不同类型的函数. . (虽然有,但是会增加不必要的复杂性). Swift编译器可能已经很慢,并且在推断类型时陷入困境,在一系列抛出函数中一直推断Throwd类型可能是一场噩梦.

一个正在运行的想法是,对于大多数错误,您将以一小部分方式来处理它们.

话虽如此,您无需添加额外的catch let error as MyErrorType子句,您只需在catch块中使用开关即可,如下所示:

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)
  }
}

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?

解决方案

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)
  }
}

这篇关于我可以限制函数在Swift中抛出的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆