Last active
August 29, 2015 14:05
-
-
Save jarsen/acfb67443db895a1d8f6 to your computer and use it in GitHub Desktop.
Exploring error patterns 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
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