Last active
August 29, 2015 14:07
-
-
Save jqsilver/9c5962bf93f5dadc9d15 to your computer and use it in GitHub Desktop.
swift error communcation: tuple versus enum
This file contains 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
// Tuple | |
// Pros: simple | |
// Issues: | |
// what if you get no result, but also no error? | |
// what if you get a result, but also an error? | |
func trySomething() -> (String?, NSError?) { | |
if let result = something() { | |
return (result, nil) | |
} else { | |
return (nil, NSError(...)) | |
} | |
} | |
func handleTrySomethingExample() { | |
let (result, error) = trySomething() | |
if let someError = error { | |
//there was an error | |
} | |
if let someResult = result { | |
//we have a result | |
} | |
} | |
// Enum | |
// Pros: limits to either error or result | |
// Cons: typing out .Worked/.Failed feels verbose | |
// forces you to use a switch-case with Result, which also feels verbose | |
// Actually you need this Box class to get it to complile | |
class Box<Type> { | |
let unbox: Type | |
init(_ val: Type) { | |
self.unbox = val | |
} | |
} | |
enum Result<Type> { | |
case Worked(Box<Type>) | |
case Failed(NSError) | |
} | |
enum Result<Type> { | |
case Worked(Type) | |
case Failed(NSError) | |
} | |
func trySomething() -> Result<String> { | |
if let result = something() { | |
return .Worked(result) | |
} else { | |
return .Failed(NSError(...)) | |
} | |
} | |
func handleTrySomethingEnumExample() { | |
switch (trySomething()) { | |
case .Worked(let result): | |
println(result) | |
case .Failed(let error): | |
println("error! " + error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment