Created
June 9, 2014 07:13
-
-
Save JensAyton/4c6df3f1ca7d32c15fef to your computer and use it in GitHub Desktop.
try() for discriminated-union error handling in Swift
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 | |
// Because the real thing crashes | |
enum Result { | |
case Value(Any) | |
case Error(NSError?) | |
} | |
func try<T>(f: (NSErrorPointer) -> T?) -> Result { | |
var error: NSError? | |
let result = f(&error) | |
if result { | |
return .Value(result!) | |
} else { | |
return .Error(error) | |
} | |
} | |
let fm = NSFileManager.defaultManager() | |
let x = try { fm.contentsOfDirectoryAtPath("/", error:$0) } | |
switch x { | |
case .Value(let v): | |
println("Success: \(v)") | |
case .Error(let e): | |
println("Error: \(e)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment