Skip to content

Instantly share code, notes, and snippets.

@ilyannn
Last active August 29, 2015 14:05
Show Gist options
  • Save ilyannn/400ee784b6f5447fadf6 to your computer and use it in GitHub Desktop.
Save ilyannn/400ee784b6f5447fadf6 to your computer and use it in GitHub Desktop.
An example of Swift style
// A different style for an example code by David Owens.
// https://github.com/owensd/json-swift/blob/master/src/Error.swift
import Foundation
/** Creates a new type that is used to represent error information in Swift.
This is a new Swift-specific error type used to return error information.
The primary usage of this object is to return it as a `Failable` or
`FailableOf<T>` from function that could fail.
Example:
`func readContentsOfFileAtPath(path: String) -> Failable<String>`
*/
public struct MyError {
typealias InfoDictionary = [String:String]
/// The error code used to differentiate between various error states.
let errorCode: Int
/// A string that is used to group errors into related error buckets.
let errorDomain: String
/// Store any custom information to be passed with the error instance.
let userInfo: InfoDictionary
/// Is this really an error?
var hasError:Bool { return !errorDomain.isEmpty }
/// Initializes a new `Error` instance.
init(code: Int, domain: String, userInfo info: InfoDictionary? = nil) {
errorCode = code
errorDomain = domain
userInfo = info ?? InfoDictionary()
}
}
/// The standard keys used in `Error` and `userInfo`.
public struct ErrorKeys {
private init() {}
static let LocalizedDescription = NSLocalizedDescriptionKey
static let LocalizedFailureReason = NSLocalizedFailureReasonErrorKey
static let LocalizedRecoverySuggestion = NSLocalizedRecoverySuggestionErrorKey
static let LocalizedRecoveryOptions = NSLocalizedRecoveryOptionsErrorKey
static let RecoveryAttempter = "NSRecoveryAttempter"
static let HelpAnchor = "NSHelpAnchor"
static let StringEncoding = "NSStringEncoding"
static let URL = "NSURL"
static let FilePath = "NSFilePath"
static private let StandardKeys = [LocalizedDescription, LocalizedFailureReason]
}
public extension MyError {
/// An initializer to be used within your own applications and libraries to
/// hide any of the ObjC interfaces from your purely Swift APIs.
init(_ error: NSErrorPointer) {
var info_dict = InfoDictionary() // 👿 TODO: Extract more keys
if let memory = error.memory {
for key in ErrorKeys.StandardKeys {
info_dict[key] = memory.userInfo?[key] as? NSString
}
}
errorCode = error.memory?.code ?? 0
errorDomain = error.memory?.domain ?? ""
userInfo = info_dict
}
}
extension MyError: Printable {
public var description: String {
return "an error '\(errorDomain)' with code \(errorCode)"
}
}
@ilyannn
Copy link
Author

ilyannn commented Aug 19, 2014

The original was published by David Owen under MIT license.

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