ikeh1024のブログ

ZennやQiitaに書くにはちょっと小粒なネタをこちらに書いています

Swiftで適当なエラーを使いたいときの実装

参考

struct MessageError: Swift.Error & CustomStringConvertible {
  var description: String
}

使用例

  • 実装例
let error = MessageError(description: "hoge")
print(error.localizedDescription)
print(error.description)
  • 出力結果
The operation couldn’t be completed. (iOSEngineerCodeCheck.MessageError error 1.)
hoge

別の案

  • もしくは以下が便利

  • String+LocalizedError.swiftを作成
#if DEBUG
extension String: LocalizedError {
    public var errorDescription: String? { self }
}
#endif
  • 呼び出し例
private func someFunction() throws {
    throw "エラーだよ"
}

do {
    try someFunction()
} catch {
    print(error.localizedDescription)  // エラーだよ
}