An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. 枚举为一组相关值定义了一个公共类型,使你在写代码的过程中可以以一种更加安全的方式来工作。 定义 你可以用enum关键字来定义一个枚举,把定义内容都放到一堆大括号里边。例如: 注意 不像C语言和oc语言,swift的case并不分配默认值。不同的case可以独立自主的定义自己的类型。 调用 1.经典调用: 2.简洁调用 The type of directionToHead is inferred when it is initialized with one of the possible values of CompassPoint. Once directionToHead is declared as a CompassPoint, you can set it to a different CompassPoint value using a shorter dot syntax: 当一个值用枚举初始化之后,那么这个值得类型就是可以推断的。一旦你确定了它是这种枚举类型,你就可以用点语法来设置为枚举的其他值。 switch语句中的枚举值 你必须穷尽每一种情况,如果不想穷尽也必须提供默认类型。否则会编译报错。 关联值 However, it is sometimes useful to be able to store associated values of other types alongside these case values. This enables you to store additional custom information along with the case value, and permits this information to vary each time you use that case in your code. 然而,有时候和这些case绑定相应的关联值更加的有用。这使你能够增加额外的信息,并且允许在代码中改变这些关联值。 默认值 枚举可以设置默认值。 这里枚举是继承的字符,因此里边不可以放置其他的类型。 1.如果枚举是整形,那么默认值是递增的。 2.如果枚举是整形,那么默认值是枚举值是case的名称。 3.使用rawValue属性,访问用例。 4.通过 let possiblePlanet = Planet(rawValue: 7)来得到对应的枚举值(注意:这个方法是可选的,需要进行判断)