Skip to content

Instantly share code, notes, and snippets.

@atomkirk
Last active August 29, 2015 14:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atomkirk/6fe89f2570a06582bd3d to your computer and use it in GitHub Desktop.
Save atomkirk/6fe89f2570a06582bd3d to your computer and use it in GitHub Desktop.
Pass In Error
// 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")
}
}
}
}
}
}
@atomkirk
Copy link
Author

atomkirk commented Jun 7, 2015

Usage

Now if anything is assigned to error, it'll be printed to the console:

NSFileManager.defaultManager().moveItemAtPath("blah", toPath: "blah2", error: &PassInError().ref)

This will print:

ERROR =================================
The operation couldn’t be completed. No such file or directory
=======================================

Or if you want to handle the error:

let error = PassInError { error in
    println("Couldn't move your dumb file: \(error)")
}
NSFileManager.defaultManager().moveItemAtPath("blah", toPath: "blah2", error: &error.ref)

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