2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

enumからNSErrorを作成する

Posted at

初めに

ErrorType が追加され使用頻度が減ったとはいえ、iOSアプリ開発ではやはり必須なNSError

自前のエラーを定義したい場合に、毎回domainやらcodeやらを指定してinitするのはめんどくさい。
というわけで、rawValue が Int なenumを使うと楽にNSError が作成できる。

コード

Enumの定義

let ErrorDomain = "com.hoge.hoge"

enum MyError: Int {
    case Hoge = 0
    case Fuga = 1

    func createError(userInfo: [String : AnyObject]? = nil) -> NSError {
        return NSError(domain: ErrorDomain, code: self.rawValue, userInfo: userInfo)
    }
}

使うときはこんな感じ

let error = MyError.Hoge.createError()
let errorWithUserInfo = MyError.Hoge.createError(["hoge" : "fuga"])

print(errorWithUserInfo) // Error Domain=com.hoge.hoge Code=0 "(null)" UserInfo={hoge=fuga}

終わりに

この方がいいんじゃね? 的なものがあったらご教示ください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?