Since NSError immutable, there is no reason to create multiple instances of the same data. Just create one, persistent instance:
let NAUnexpectedResponseTypeError = NSError(domain: "MyDomain", code: 6782, userInfo: [NSLocalizedDescriptionKey: "The object fetched by AFNetworking was not of an expected type."] )
If you have a situation that is not constant, then it is almost always better to extend, rather than a subclass of NSError . For instance:
extension NSError { class func MyError(code code:code, message: String) -> NSError { return NSError(domain: "MyDomain", code: code, userInfo: [NSLocalizedDescriptionKey: message]) } }
This type of extension (as a category) has a long history in ObjC and is a good template for Swift (if you cannot easily use enum ErrorTypes, which are even better than Swift).
In many cases, it’s even easier for me to simply have a top-level function for this, rather than extending an NSError . For instance:
private func makeError(code code:code, message: String) -> NSError { return NSError(domain: "MyDomain", code: code, userInfo: [NSLocalizedDescriptionKey: message]) }
(Personally, I use these functions all the time in Swift when I have to use NSError . In ObjC I usually used categories on NSError . I don’t know why I changed, but it feels more natural.)
source share