swift的枚举

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)来得到对应的枚举值(注意:这个方法是可选的,需要进行判断)
这里写图片描述
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值