Created
March 23, 2017 06:55
-
-
Save suzukimilanpaak/2387da938afa74943c50271318a29b23 to your computer and use it in GitHub Desktop.
[Swift] try, try!, try?
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 | |
enum ThrowableError: Error { case BadError } | |
func doSomething(_ occursError: Bool) throws -> String { | |
if !occursError { | |
return "Everything is ok" | |
} else { | |
throw ThrowableError.BadError | |
} | |
} | |
func doSomeOtherThing() { | |
let resultA = try! doSomething(false) | |
// let resultB = try! doSomething(true) | |
// => 実行時エラー | |
if let resultC = try? doSomething(true) { | |
print(resultC) | |
} else { | |
print("error occurs") | |
} | |
do { | |
let resultD = try doSomething(true) | |
} catch { | |
print("error occurs") | |
} | |
} | |
doSomeOtherThing() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment