Skip to content

Instantly share code, notes, and snippets.

@zyg-github
Forked from erica/error.swift
Last active December 7, 2015 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zyg-github/45a0935fcc075ddf706b to your computer and use it in GitHub Desktop.
Save zyg-github/45a0935fcc075ddf706b to your computer and use it in GitHub Desktop.
//http://swift.gg/2015/11/27/implementing-printing-versions-of-try-and-try-on-steroids-in-swiftlang/
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