-
-
Save onmyway133/9b638a7ba09a87813d31 to your computer and use it in GitHub Desktop.
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 | |
// Generic Error | |
public struct Error: ErrorType {let reason: String} | |
/** | |
Printing version of try? Call either with standard or autoclosure approach | |
``` | |
let contents = attempt{try NSFileManager.defaultManager().contentsOfDirectoryAtPath(fakePath)} | |
let contents = attempt{try NSFileManager.defaultManager().contentsOfDirectoryAtPath(XCPlaygroundSharedDataDirectoryURL.path!)} | |
``` | |
- Returns: Optional that is nil when the called closure throws | |
*/ | |
public func attempt<T>(source source: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, closure: () throws -> T) -> Optional<T>{ | |
do { | |
return try closure() | |
} catch { | |
let fileName = (file as NSString).lastPathComponent | |
let report = "Error \(fileName):\(source):\(line):\n \(error)" | |
print(report) | |
return nil | |
} | |
} | |
/** | |
A printing alternative to try? that returns Boolean value | |
``` | |
let success = attemptFailable{try "Test".writeToFile(fakePath, atomically: true, encoding: NSUTF8StringEncoding)} | |
``` | |
- Returns: Boolean value, false if the called closure throws an error, true otherwise | |
*/ | |
public func attemptFailable(source source: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, closure: () throws -> Void) -> Bool { | |
do { | |
try closure() | |
return true | |
} catch { | |
let fileName = (file as NSString).lastPathComponent | |
let report = "Error \(fileName):\(source):\(line):\n \(error)" | |
print(report) | |
return false | |
} | |
} | |
/** | |
Slightly more informative version of try!. When shouldCrash is set to false, | |
execution will continue without a fatal error even if an error is thrown | |
``` | |
doOrDie(shouldCrash: false, closure: {try "Test".writeToFile(fakePath, atomically: true, encoding: NSUTF8StringEncoding)}) | |
// or | |
doOrDie(shouldCrash:false){try NSFileManager.defaultManager().removeItemAtURL(fakeURL)} | |
// or | |
doOrDie{try "Test".writeToFile(fakePath, atomically: true, encoding: NSUTF8StringEncoding)} | |
``` | |
*/ | |
public func doOrDie(source: String = __FUNCTION__, | |
file: String = __FILE__, line: Int = __LINE__, shouldCrash: Bool = true, closure: () throws -> Void) { | |
let success = attemptFailable(source: source, file: file, line: line, closure: closure) | |
if shouldCrash && !success {fatalError("Goodbye cruel world")} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment