LoginSignup
32
15

More than 5 years have passed since last update.

Swift5のError型のちょっと便利になった点について

Last updated at Posted at 2019-04-13

Swift5でResult型が公式にサポートされました:tada:

処理の結果をSuccess, FailureとしてパターンマッチングできるEnumです。

定義

enum Result<Success, Failure> where Failure : Error

使い方

switch result {
case .success(let someValue):
  // someValueを使った処理
case .failure(let error):
    print(error.message)
}

今までライブラリや似たような自作のEnumで同じことをやっていたので、何が嬉しいのか?と思ったのですが、リリースノートにこんな一文がありました。

D2jktT1U0AIQZE-.jpg

As part of this addition, the Error protocol now conforms to itself, which makes working with errors in a generic context easier. (SE-0235) (21200405)

Errorがそれ自身に準拠した型としてサポートされた:tada:

いままで

今まではErrorはただの存在型としてのProtocolであるため、それ自身を型として利用できずコンパイルエラーになります。
そのためただログ出力したり、Crashlyticsに通知するために扱うだけでもErrorに準拠した型を別途用意せねばならず面倒でした

(Result<Bool, Error>) -> Void
// Using 'Error' as a concrete type conforming to protocol 'Error' is not supported

これから

Resultが公式サポートされた一環として、Error型がそのまま使えるので地味に便利になりました。

どうやって実現しているのか

言語レベルの特別措置として実現しているようです

PR
https://github.com/apple/swift/pull/21073/commits/7fea4b845b1de824d675372df2341472f4e41c34

合わせて読みたい
Swiftのprotocolの存在型がそれ自身のprotocolに準拠しない理由

32
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
15