Swift 基础 枚举详解(代码)
一直觉得自己写的不是技术,而是情怀,一个个的教程是自己这一路走来的痕迹。靠专业技能的成功是最具可复制性的,希望我的这条路能让你们少走弯路,希望我能帮你们抹去知识的蒙尘,希望我能帮你们理清知识的脉络,希望未来技术之巅上有你们也有我。
枚举源码地址
最常用值的互相切换
基本的枚举类型
注意:与C和Objective-C不同,Swift枚举情况在创建时不分配默认整数值。在Weight例子中,light,Mid和Heavy不等于隐式0,1和2。
enum Weight {case lightcase midcase heavy
}
使用
let weight = Weight.light
print("weight: \(weight)")
打印结果
OC的枚举值只支持Int一种类型,Swift的枚举值支持四种类型
对于Int类型的枚举
enum Age: Int {case young = 0case middle = 1case old = 2
}
let age = Age.youngprint("age: \(age)")
上面的代码有一个缩写的方法
enum Age : Int {case young ,middle , old
}let age = Age.old
使用枚举的rawValue属性来访问其原始值:
let ageRawValue = Age.old.rawValue
对于字符串类型的枚举成员,举例如下:
enum DogName:String {case taidi = "taidi"case fadou = "fadou"case xiaogou = "xiaogou"
}
let name = DogName.taidi
print("name: \(name)")
上面的例子对于字符串的枚举成员,隐式原始值为该枚举成员变量的名称,不过它规定要int类型才行
enum DogNname:Int {case taidicase fadoucase xiaogoucase guibing
}
let dogName = DogNname(rawValue: 3)
print("douName: \(dogName!)")
嵌套枚举
enum Dog {enum Food {case noodlescase dumplingcase meat}enum Toys {case basketBallcase footBall}case taidiscase fanius
}let pet = Dog.taidis
print("pet: \(pet)")let food = Dog.Food.dumpling
print("food: \(food)")let toys = Dog.Toys.basketBall
print("toys: \(toys)")
迭代枚举(die dai)
enum Cat:CaseIterable {case bigCatcase middleCatcase oldCat
}
let numOfDogKind = Cat.allCases.count
print("numOfDogKind = \(numOfDogKind)")
for dogKind in Cat.allCases{print(dogKind)
}
关联值
我们可以定义Swift枚举来存储任何给定类型的关联值,而且每种枚举情况的值类型可以不同。
enum Pet{//名字和年龄case dog(String,Int)//体重case cat(Float)
}
var result = Pet.dog("老七", 3)
result = Pet.cat(2.0)
print(result)//cat(2.0)
switch result {
case .dog(let name, let age):print("dog: name = \(name), age = \(age).")
case .cat(let weight):print("cat: weight = \(weight)公斤")//cat: weight = 2.0公斤
}
如果一个枚举成员的所有关联值都被提取为常量,或者都被提取为变量,为了简洁,你可以只在成员名称前标注一个let或者var:
var result = Pet.dog("老七", 3)
result = Pet.cat(2.0)
switch result {
case let .dog(name,age):print("dog: name = \(name), age = \(age).")
case let .cat(weight):print("cat: weight = \(weight)公斤")
}
包含枚举: 同样地,你也能够在structs或classes中内嵌枚举。举例:
struct DaDog {enum DogKind {case jinmaocase taijicase fadou}enum Food {case noodlescase dumplingcase meat}let kind : DogKindlet food : Food}
let dog = DaDog(kind: .fadou, food: .dumpling);
print(dog.kind)
方法和属性
enum Device {case iPad, iPhone, AppleTV, AppleWatchfunc introduced() -> String {switch self {case .iPad: return "iPad"case .iPhone: return "iPhone"case .AppleWatch: return "AppleWatch"case .AppleTV: return "AppleTV"}}}
很清晰,我们定义了一个设备枚举,有iPad, iPhone, AppleTV, AppleWatch,还有一个介绍的方法。这里的introduced方法,你可以认为枚举是一个类,introduced是一个成员方法,Device.iPhone就是一个Device的实例,case们是他的属性,好了,有了这个对像,Device.iPhone可以认为,Device里面有一个匿名属性,现在设置这个属性为iPhone。好了,introduced里面的switch self,其实就是遍历这个匿名属性的所有场景,如iPad,iPhone等,然后根据不同的场景返回不同的值。
print(Device.iPhone.introduced())
属性
增加一个存储属性到枚举中不被允许,但你依然能够创建计算属性。当然,计算属性的内容都是建立在枚举值下或者枚举关联值得到的。
enum Devices {case iPads, iPhonesvar year: Int {switch self {case .iPhones: return 2007case .iPads: return 2010}}}
print(Devices.iPhones.year)
静态方法
enum Device {case iPad, iPhone, AppleTV, AppleWatchfunc introduced() -> String {switch self {case .iPad: return "iPads"case .iPhone: return "iPhones"case .AppleWatch: return "AppleWatchs"case .AppleTV: return "AppleTVs"}}static func fromSlang(term: String) -> Device? {if term == "iWatch" {return .AppleWatch}return nil}}
print(Device.fromSlang(term: "iWatch"))
Swift也允许你在枚举中使用协议(Protocols)和协议扩展(Protocol Extension)。
Swift协议定义一个接口或类型以供其他数据结构来遵循。enum当然也不例外。我们先从Swift标准库中的一个例子开始.
CustomStringConvertible是一个以打印为目的的自定义格式化输出的类型。
该协议只有一个要求,即一个只读(getter)类型的字符串(String类型)。我们可以很容易为enum实现这个协议。
protocol CustomStringConvertible {var description: String { get }
}enum Trade :CustomStringConvertible{case Buy(stock:String,amount:Int)case Sell(stock:String,amount:Int)var description: String {switch self {case .Buy(_, _):return "Buy"case .Sell(_, _):return "Sell"}}
}
print(Trade.Buy(stock: "003100", amount: 100).description)
扩展
枚举也可以进行扩展。最明显的用例就是将枚举的case和method分离,这样阅读你的代码能够简单快速地消化掉enum内容,紧接着转移到方法定义:
import Foundationenum Device {case iPad, iPhone, AppleTV, AppleWatch}extension Device: CustomStringConvertible{func introduced() -> String {switch self {case .iPad: return "iPad"case .iPhone: return "iPhone"case .AppleWatch: return "AppleWatch"case .AppleTV: return "AppleTV"}}var description: String {switch self {case .iPad: return "iPad"case .iPhone: return "iPhone"case .AppleWatch: return "AppleWatch"case .AppleTV: return "AppleTV"}}
}
使用
print("introduced: \(Device.iPad.introduced())")print("description: \(Device.iPad.description)")
Swift 基础 枚举详解(代码)相关推荐
- 五分钟搞懂后缀数组!后缀数组解析以及应用(附详解代码)
为什么学后缀数组 后缀数组是一个比较强大的处理字符串的算法,是有关字符串的基础算法,所以必须掌握. 学会后缀自动机(SAM)就不用学后缀数组(SA)了?不,虽然SAM看起来更为强大和全面,但是有些SA ...
- java基础(十三)-----详解内部类——Java高级开发必须懂的
java基础(十三)-----详解内部类--Java高级开发必须懂的 目录 为什么要使用内部类 内部类基础 静态内部类 成员内部类 成员内部类的对象创建 继承成员内部类 局部内部类 推荐博客 匿名内部 ...
- python命名空间和闭包_Python函数基础实例详解【函数嵌套,命名空间,函数对象,闭包函数等】...
本文实例讲述了Python函数基础用法.分享给大家供大家参考,具体如下: 一.什么是命名关键字参数? 格式: 在*后面参数都是命名关键字参数. 特点: 1.约束函数的调用者必须按照Kye=value的 ...
- python编程语法大全-Python编程入门——基础语法详解
今天小编给大家带来Python编程入门--基础语法详解. 关于怎么快速学python,可以加下小编的python学习群:611+530+101,不管你是小白还是大牛,小编我都欢迎,不定期分享干货 每天 ...
- python编程语法-Python编程入门——基础语法详解
今天小编给大家带来Python编程入门--基础语法详解. 一.基本概念 1.内置的变量类型: Python是有变量类型的,而且会强制检查变量类型.内置的变量类型有如下几种: #浮点 float_num ...
- python编程if语法-Python编程入门基础语法详解经典
原标题:Python编程入门基础语法详解经典 一.基本概念 1.内置的变量类型: Python是有变量类型的,而且会强制检查变量类型.内置的变量类型有如下几种: #浮点 float_number = ...
- python编程语法-Python编程入门——基础语法详解(经典)
今天小编给大家带来Python编程入门--基础语法详解.温馨提示: 亮点在最后! 在这里还是要推荐下我自己建的Python开发学习群:301056051,群里都是学Python开发的,如果你正在学习P ...
- JVM之常用基础参数详解
JVM之常用基础参数详解 目录 常用基础参数内存Xms,Xmx讲解 常用基础参数栈内存Xss讲解 常用基础参数元空间MetaspaceSize讲解 常用基础参数PrintGCDetails回收前后对比 ...
- python基础编程语法-Python编程入门——基础语法详解
今天小编给大家带来Python编程入门--基础语法详解. 一.基本概念 1.内置的变量类型: Python是有变量类型的,而且会强制检查变量类型.内置的变量类型有如下几种: #浮点 float_num ...
最新文章
- iOS 三种类型的Block
- sed awk 笔记(二)
- SQL Azure SU3 现已在全球6座数据中心开始启用
- 又见奇葩乘客!醉酒男子与人发生冲突迫使飞机返航
- 手把手教你搭建Linux开发环境(VMware+Ubuntu)(四)——gcc编译器的安装和使用
- 解析时代需要什么样的根目录,中国科技需要什么样的根技术
- 软设考试笔记--UML建模
- php的cgi的设置,apache中配置php支持模块模式、cgi模式和fastcgi模式
- ORA-28000: the account is locked
- 机器学习训练建模、集成模型、模型评估等代码总结(2019.05.21更新)
- python面向对象大段代码_python粗谈面向对象(一)
- 利用EfficientNet-B5从眼底摄影检测糖尿病视网膜病变的严重程度
- Jquery,ajaxFileUpload插件完成图片上传
- 访问限制:由于对必需的库E:\j2sdk\jre\lib\rt.jar具有一定限制,因此无法访问类型JFrame
- MyBioSource p53 肿瘤抑制蛋白 (TP53),多克隆抗体
- 谷歌十年愚人节,「玩笑」背后是美好生活的企盼
- an error occurred while contacting the respository
- 蓝桥杯:第39级台阶
- 生成树协议三姐妹:STP、RSTP 和 MSTP,附思科和华为双厂商命令示例
- 净水行业首家,安吉尔新水效国标检测能力获CNAS认可