LoginSignup
0
1

More than 1 year has passed since last update.

Swiftエラー処理

Posted at

Swiftエラー処理

swiftは静的型付け言語であり、安全性の高い言語 ではあるがエラーの発生は避けられないのでエラーを適切に処理する必要がある。

do-catch構文

書き方

do {
    try メソッドを書く
} catch {
    // エラーが発生した場合の処理を書く
}

tryはtry?try!で機能が違う。?はエラーになっても無視して実行するが、!は強制アンラップをするのでアプリがクラッシュする可能性がある。
もしエラーが起こりうる関数を定義したらあわせてthorowsキーワードを引数の後に書く必要がある

Result型のエラー処理

Result型のエラー処理は正確にエラー内容をかくにんすることができる
列挙型の形をとり、case .successとcase .failureのケースを持つ。
ライブラリでswitch文で条件分岐する書き方がよくある

public enum Result<Success, Failure: Error> {
    case success(Success)
    case failure(Failure)
}

下記の書き方でAlamofireで使用するイメージ

 switch result {
        case .success:
            print("成功")
        case .failure:
            print("失敗")
        }

assert,precondition

ある条件を満たした場合にプログラムを終了する。
ビルドの状態によって最適化されているが、基本preconditionでも同じ使用方法である。基本デバックでassertを使う

func method(_ arg: Int) {
//if文のように使用する
  assert(arg < 0, "プログラム終了")//assertがpreconditionでも同じ挙動をする

  print("処理実行されない")
}
method(-1)

assertionFailure

強制的にプログラムを終了させる

func method(_ arg: Int) {
  assertionFailure("プログラム終了")
  print("処理を実行されない")
}

fatalError

強制的にプログラムを終了させる(assetは条件を満たした場合のみ)

fatal.swift
func method() {
  fatalError("プログラム終了")
  print("処理実行されない)
}
method()
0
1
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
0
1