Skip to content

Instantly share code, notes, and snippets.

@haranicle
Last active August 29, 2015 14:25
Show Gist options
  • Save haranicle/d52aaa62595ad138b539 to your computer and use it in GitHub Desktop.
Save haranicle/d52aaa62595ad138b539 to your computer and use it in GitHub Desktop.
guardについて #cswift #CodePiece
guard let value != 0 else {
// ここでスコープを抜ける処理
return
break
continue
fatalError()
}
// 上の条件が満たされていることを前提としたコードが書ける
print( 100 / value )
// きもいけどこんなふうに書ける
guard let path = getPath() where path.hasPrefix("hoge") {
fatalError()
}
@es-kumagai
Copy link

1 行目の補足ですけど guard let value != 0 else { の場合は let なしです。

let を使うときは、新しい変数で受けたいとき、たとえば Optional Binding で guard let value = optionalValue else { としたい場合などです。

@es-kumagai
Copy link

12 行目は 行末の { の前に else を挟みます。

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