Created
June 9, 2014 00:46
-
-
Save romaonthego/2c91ea9cb828bcd4f1e1 to your computer and use it in GitHub Desktop.
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
// 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