Created
February 14, 2017 02:50
-
-
Save dictav/fa6325093fb66f31a26d4489e50ccacb to your computer and use it in GitHub Desktop.
swift のエラーハンドリングをGoっぽく書けないかなーと言うあがき
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
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!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
とか書けちゃうからあんまり意味ないね