Skip to content

Instantly share code, notes, and snippets.

@jqsilver
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jqsilver/9c5962bf93f5dadc9d15 to your computer and use it in GitHub Desktop.
Save jqsilver/9c5962bf93f5dadc9d15 to your computer and use it in GitHub Desktop.
swift error communcation: tuple versus enum
// 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