Last active
December 1, 2016 06:39
-
-
Save mono0926/ab9af9960862a385fff44e8b4555585f to your computer and use it in GitHub Desktop.
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
class MyClass { | |
var value: Int? | |
// nilである時に呼び出されることを普通に想定しているならこんな感じ | |
func someMethod1() { | |
guard let value = value else { | |
return | |
} | |
print(value) | |
} | |
// nilである時に呼び出されるのが想定外ならこんな感じ(デバッグ環境でのみクラッシュ) | |
func someMethod2() { | |
guard let value = value else { | |
assert(false) | |
return | |
} | |
print(value) | |
} | |
// nilである時に呼び出されえ後続の処理が続行されるのがマズイならこんな感じ(リリース環境でもクラッシュ) | |
func someMethod3() { | |
guard let value = value else { | |
fatalError() | |
return | |
} | |
print(value) | |
} | |
// ?を用いてオプショナルチェーンするのも、このパスではnilでもOKという明確な意図が無いと良くないと思っている(個人的には滅多に使わない) | |
func someMethod4() { | |
print(value?.description) | |
// 以下も、基本的にはオプショナルチェーン使わずに初期化時にnilの考慮したり`!`アクセスしたりするべき | |
let url = URL(string: "http://qiita.com/mono0926") | |
print(url?.path) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment