Skip to content

Instantly share code, notes, and snippets.

@takasek
Created March 3, 2016 23:50
Show Gist options
  • Save takasek/8c1f118756dad04619cf to your computer and use it in GitHub Desktop.
Save takasek/8c1f118756dad04619cf to your computer and use it in GitHub Desktop.
switchとタプルの組み合わせは、ネスト1段でたくさんのケースを網羅的に記述できるので大好きです。 #CodePiece
enum Animal {
case Cat
case Dog(kind: String)
case Human
}
func hoge(animal: Animal, isTamed: Bool, age: Int) {
switch (animal, isTamed) {
case (.Cat, true):
print("tamed cat")
case (.Cat, _):
print("wild cat")
case (.Dog(let kind), true) where kind == "Pochi":
print("tamed Pochi")
case (.Dog(let kind), true):
print("tamed dog:", kind)
case (.Dog(let kind), _):
print("wild dog:", kind)
case (.Human, true):
print("tamed human")
case (.Human, _) where age < 20:
print("wild child")
// case (.Human, _): ←このケースがないと網羅できないのでビルドエラー
} //error: switch must be exhaustive, consider adding a default clause
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment