LoginSignup
1
0

SwiftのThrowsとthrow

Posted at

SwiftのThrowsとthrowとは?

Swiftでエラー処理をするときに、提供されている機能でthrowとThrowがある。

throwキーワードは、エラーをスローするために使用され、Throwsキーワードはメソッド宣言で指定されます。

エラー処理の作り方

Enumを使用して、Error型の列挙型を作ります。ただの定数ですね。errorのcaseに対して必要なだけ書きます。

// throwing errors
enum Errors: Error {
    case OutOfStock
}

if文でエラーチェックする処理を書きます。メソッドに、throwsキーワードをつけると、Enumで定義したエラーを使うことができます。

throwを使うには、do catchの中で使う必要があります。

import UIKit

// throwing errors
enum Errors: Error {
    case OutOfStock
}

struct Stock {
    var totalLamps = 5
    mutating func sold(amount: Int) throws {
        if amount > totalLamps {
            throw Errors.OutOfStock
        } else {
            totalLamps = totalLamps - amount
        }
    }
}

var myStock = Stock()

do {
    try myStock.sold(amount: 8)
} catch {
    print(error)// OutOfStock
}

しかし、エラーを気にしない場合は、tryキーワードが強制的に結果を返すようにすることができます。メソッドがエラーをthrowした場合は、nilを返すためcatchステートメントを実行する。do catchを削除して、try?に修正してみましょう。

import UIKit

// throwing errors
enum Errors: Error {
    case OutOfStock
}

struct Stock {
    var totalLamps = 5
    mutating func sold(amount: Int) throws {
        if amount > totalLamps {
            throw Errors.OutOfStock
        } else {
            totalLamps = totalLamps - amount
        }
    }
}

var myStock = Stock()

try? myStock.sold(amount: 8)// nil

場合によっては、throwメソッドがerrorをthrowしないことが事前にわかっているため不要なコードの記述を避けたいことがあります。この場合はtry?を使用できます。

購入したランプの合計をチェックして大きいかどうかを確認してみます。

import UIKit

// throwing errors
enum Errors: Error {
    case OutOfStock
}

struct Stock {
    var totalLamps = 5
    mutating func sold(amount: Int) throws {
        if amount > totalLamps {
            throw Errors.OutOfStock
        } else {
            totalLamps = totalLamps - amount
        }
    }
}

var myStock = Stock()
// 在庫を3個超えているか?
if myStock.totalLamps > 3 {
    try! myStock.sold(amount: 3)
}
print("ランプの在庫は: \(myStock.totalLamps)")// ランプの在庫は: 2

まとめ

SwiftのthrowとThrowsについて学習してみました。違いはなんだと混乱してしまいますよね。Throwsの方は、メソッドにつけて、throwはエラーを返す処理の中に書くものでした。

1
0
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
1
0