Swift では、エラーは ErrorType プロトコルに準拠する型の値で表現されます。この空のプロトコルによって、エラー処理に使用される型であることを示します。

Swift の列挙型は、関連するエラーのグループをモデル化するのに特によく適していて、伝達されるエラーの特徴についての付加情報を考慮した関連値を持つことができます。

enum VendingMachineError: ErrorType {
    case InvalidSelection
    case InsufficientFunds(coinsNeeded: Int)
    case OutOfStock
}

エラーをスローすることで、何か予期しないことが起き、通常の実行フローが継続できないことを示します。エラーをスローするために throw 文を使用します。例えば、次のコードは自動販売機にコインを 5 枚追加する必要があることを示すエラーを投げています。

throw VendingMachineError.InsufficientFunds(coinsNeeded: 5)

Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.