参考
struct MessageError: Swift.Error & CustomStringConvertible {
— おもちメタル (@omochimetaru) 2022年11月5日
var description: String
}
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
別の案
- もしくは以下が便利
私は
— treastrain / Tanaka.R (@treastrain) 2022年11月5日
extension String: LocalizedError {
public var errorDescription: String? { self }
}
とどこかに書いて、
throw "エラーだよ"
としています(extension 自体がリリースに入り込まないように #\if DEBUG で囲むなど) https://t.co/wq4WZjuRC2
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) // エラーだよ }