Skip to content

Instantly share code, notes, and snippets.

@dictav
Created February 14, 2017 02:50
Show Gist options
  • Save dictav/fa6325093fb66f31a26d4489e50ccacb to your computer and use it in GitHub Desktop.
Save dictav/fa6325093fb66f31a26d4489e50ccacb to your computer and use it in GitHub Desktop.
swift のエラーハンドリングをGoっぽく書けないかなーと言うあがき
import Foundation
func result<T>(_ closure: @autoclosure () throws -> T) -> (T?, Error?) {
do {
let a = try closure()
return (a, nil)
} catch (let err) {
return (nil, err)
}
}
func hoge(_ v: Int) throws -> Int {
if v == 0 {
throw NSError(domain:"Error", code:1)
}
return v
}
do {
let a = try hoge(1)
print(a)
} catch (let err) {
print(err)
}
let (n, err) = result( try hoge(1) )
guard err == nil else {
print(err!)
exit(0)
}
print(n!)
@dictav
Copy link
Author

dictav commented Feb 14, 2017

let n = result( try hoge(1) )

とか書けちゃうからあんまり意味ないね

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment