Last active
August 29, 2015 14:22
-
-
Save atomkirk/6fe89f2570a06582bd3d to your computer and use it in GitHub Desktop.
Pass In Error
This file contains 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
// PassInError.swift | |
// Created by Adam Kirk on 6/6/15. | |
import Foundation | |
typealias PassInErrorBlock = (error: NSError) -> Void | |
class PassInError: NSObject { | |
dynamic var ref: NSError? | |
let block: PassInErrorBlock? | |
init(block: PassInErrorBlock? = nil) { | |
self.block = block | |
super.init() | |
self.addObserver(self, forKeyPath: "ref", options: nil, context: nil) | |
} | |
deinit { | |
self.removeObserver(self, forKeyPath: "ref") | |
} | |
// MARK: - KVO | |
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { | |
if let smartError = object as? PassInError { | |
if keyPath == "ref" { | |
if let error = self.ref { | |
if let block = self.block { | |
block(error: error) | |
} | |
if let underlyingError = error.userInfo?[NSUnderlyingErrorKey] as? NSError { | |
println("ERROR =================================\n" + | |
"\(underlyingError.localizedDescription)\n" + | |
"=======================================\n") | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Now if anything is assigned to error, it'll be printed to the console:
This will print:
Or if you want to handle the error: