Last active
May 27, 2025 15:25
-
-
Save florieger/50205f96fa9a9705c4fc161b39495fa4 to your computer and use it in GitHub Desktop.
Swift Error handling, bridging the gap between Error and NSError.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public typealias ACError = NSError | |
extension ACError { | |
public convenience init(message: String) { | |
var infoDict = [String: Any]() | |
infoDict[NSLocalizedDescriptionKey] = message | |
self.init(domain: "com.appcron", code: 0, userInfo: infoDict) | |
} | |
public var message: String { | |
// Use localizedDescription instead in infoDict, | |
// since some CoreData errors have a localizedDescription but no entry in the dictionary. | |
localizedDescription | |
} | |
} | |
extension Error { | |
public var message: String { | |
if let errorWithMessage = self as? ErrorWithMessage { | |
errorWithMessage.message | |
} else { | |
// Error can always be cast to NSError | |
(self as NSError).message | |
} | |
} | |
} | |
// This protocol enables other structs of Type Error to override the message property. | |
public protocol ErrorWithMessage { | |
var message: String { get } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment