Skip to content

Instantly share code, notes, and snippets.

@nicolas-miari
Last active May 22, 2017 07:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolas-miari/f9a81a7753f2c1be8be9 to your computer and use it in GitHub Desktop.
Save nicolas-miari/f9a81a7753f2c1be8be9 to your computer and use it in GitHub Desktop.
Swift extension that provides convenient shorthands for initializing `NSError` objects.
/**
Provides convenient shorthands for initializing `NSError` objects.
*/
extension NSError {
/**
Same as `init(domain:code:userInfo:)`, but `domain` defaults to the app's
bundle indentifier.
*/
convenience init(code: Int, userInfo: [NSObject : AnyObject]?) {
let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier!
self.init(domain: bundleIdentifier, code: code, userInfo: userInfo)
}
/**
Same as `init(code:userInfo:)`, but `userInfo` defaults to
`[NSLocalizedDescriptionKey : localizedDescription]`. This is the shortest way
to initialize an NSError instance.
###Examples:
let error1 = NSError(code: -1, localizedDescription: "Something happened!")
let error2 = NSError(localizedDescription: "Something more happened!")
*/
convenience init (code: Int = 0, localizedDescription:String) {
self.init(code: code, userInfo: [NSLocalizedDescriptionKey : localizedDescription])
}
}
@nicolas-miari
Copy link
Author

I got tired of having to type NSError(domain: ???, code: ???, userInfo: [NSLocalizedDescriptionKey: "...."]) every time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment