Skip to content

Instantly share code, notes, and snippets.

@romaonthego
Created June 9, 2014 00:46
Show Gist options
  • Save romaonthego/2c91ea9cb828bcd4f1e1 to your computer and use it in GitHub Desktop.
Save romaonthego/2c91ea9cb828bcd4f1e1 to your computer and use it in GitHub Desktop.
// Playground - noun: a place where people can play
import Foundation
enum Result<ValueType, ErrorType> : LogicValue {
case Value(ValueType)
case Error(ErrorType)
var successful : Bool {
get {
switch self {
case .Value: return true
case .Error: return false
}
}
}
var value : ValueType? {
get {
switch self {
case .Value(let v): return v
case .Error: return nil
}
}
}
var error : ErrorType? {
get {
switch self {
case .Value: return nil
case .Error(let e): return e
}
}
}
func getLogicValue() -> Bool {
return self.successful
}
}
// #############################################################################
// This example shows a function that just wants to return success or failure
func F1() -> Result<Void, String> {
return .Value()
}
// This example shows a function that just returns a string value
func F2() -> Result<String, Int> {
return .Value("This was a triumph")
}
// This example shows a function that fails with an error code
func F3() -> Result<String, Int> {
return .Error(-666)
}
// If based handling
let result = F1()
if result {
println(result.value)
} else {
println(result.error)
}
// Switch based handling - have to handle all cases
switch F1() {
case .Value(let v):
println(v)
case .Error(let e):
println(e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment