Skip to content

Instantly share code, notes, and snippets.

@jarsen
Last active August 29, 2015 14:05
Show Gist options
  • Save jarsen/acfb67443db895a1d8f6 to your computer and use it in GitHub Desktop.
Save jarsen/acfb67443db895a1d8f6 to your computer and use it in GitHub Desktop.
Exploring error patterns in swift
enum Fallible<T> {
case Error(NSError)
case Some(T)
init(value: T) {
self = .Some(value)
}
init(error: NSError) {
self = .Error(error)
}
}
func function1(#fail: Bool) -> (value: String?, error: NSError?) {
if (fail) {
return (nil, NSError(domain: "foo", code: 0, userInfo: nil))
}
else {
return ("Did not fail", nil)
}
}
func function2(#fail: Bool) -> Fallible<String> {
if (fail) {
return Fallible(error: NSError(domain: "foo", code: 0, userInfo: nil))
}
else {
return Fallible(value: "Did not fail")
}
}
func try<T>(try: ()->Fallible<T>, #success:T->(), #failure: NSError->()) {
let result = try()
switch(result) {
case let .Failure(error):
failure(error)
case let .Success(value):
success(value)
}
}
let attempt: ()->Fallible<String> = {
let error = NSError(domain: "foo", code: 0, userInfo: nil)
return Fallible(error: error)
}
let success : (String)->() = { s in println(s) }
let failure: (NSError)->() = { e in println("Error: \(e)") }
try(attempt, success: success, failure: failure)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment