列挙型の個々の値を、switch
文で利用することができます。
directionToHead = .South
switch directionToHead {
case .North:
print("Lots of planets have a north")
case .South:
print("Watch out for penguins")
case .East:
print("Where the sun rises")
case .West:
print("Where the skies are blue")
}
// "Watch out for penguins" と出力
このコードを次のように読むことができます。
「directionToHead
の値について考える。.North
と一致するケースでは、"Lots of planets have a north"
と出力する。.South
と一致するケースでは、"Watch out for penguins"
と出力する。」
…など。
Control Flow で説明されているように、列挙型のケースで switch
文を網羅的にする必要があります。.West
の case
を省略した場合、ケースが CompassPoint
の完全なリストでなくなるため、このコードをコンパイルできなくなります。網羅する必要があるため、列挙型のケースを誤って省略してしまうことがありません。
列挙型のすべてのケースを case
とすることが適さない場合には、明示的に記述していないケースをカバーするために default
ケースを記述することができます。
let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
// "Mostly harmless" と出力
Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.