发布于 2015-06-14 01:54:06 | 154 次阅读 | 评论: 0 | 来源: 网络整理

匹配枚举值和Switch语句

你可以匹配单个枚举值和switch语句:


directionToHead = .South
switch directionToHead {
case .North:
    println("Lots of planets have a north")
case .South:
    println("Watch out for penguins")
case .East:
    println("Where the sun rises")
case .West:
    println("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这种情况,上面那段代码将无法通过编译,因为它没有考虑到CompassPoint的全部成员。全面性的要求确保了枚举成员不会被意外遗漏。

当不需要匹配每个枚举成员的时候,你可以提供一个默认default分支来涵盖所有未明确被提出的任何成员:


let somePlanet = Planet.Earth
switch somePlanet {
case .Earth:
    println("Mostly harmless")
default:
    println("Not a safe place for humans")
}
// 输出 "Mostly harmless”
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务