Swift_枚举


点击查看源码

空枚举

//空枚举
enum SomeEnumeration {
// enumeration definition goes here
}

枚举基本类型

//枚举基本类型
enum CompassPoint {
case north
case south
case east
case west
}

简写

//简写
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}

枚举语法

//枚举语法
func testEnumerationSyntax() { //使用
var directionToHead = CompassPoint.west
//可不写 前面的枚举名
directionToHead = .east
print("\(directionToHead)") /* print east */
}

枚举匹配

//枚举匹配
func testMatchingEnumeration() { var directionToHead = CompassPoint.south //if匹配
if directionToHead == CompassPoint.south {
directionToHead = .east
} //switch匹配
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")
default:
print("default")
} /* print Where the sun rises */
}

关联值

//关联值
func testAssociatedValues() {
//枚举可以和结构体类型的数据关联使用
enum Barcode {
case upca(Int, Int, Int, Int)
case qrCode(String)
} // 初始化
var productBarcode = Barcode.upca(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP") //匹配
switch productBarcode {//有警告 要求是常数
case .upca(let numberSystem, let manufacturer, let product, let check):
print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
} //可以不写let
switch productBarcode {
case let .upca(numberSystem, manufacturer, product, check):
print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
print("QR code: \(productCode).")
} /* print QR code: ABCDEFGHIJKLMNOP.
QR code: ABCDEFGHIJKLMNOP. */
}

原始值

//原始值
func testRawValues() {
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
} //隐式分配原始值
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
} //原始值为属性名转换
enum CompassPoint: String {
case North, South, East, West
} print("\(Planet.earth.rawValue)")
print("\(CompassPoint.West.rawValue)") // 通过原始值初始化
let possiblePlanet = Planet(rawValue: 7)
print("\(possiblePlanet)")
let positionToFind = 9
print("\(possiblePlanet)") // 当原始值不匹配时,返回为nil
if let somePlanet = Planet(rawValue: positionToFind) {
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
} /* print 3
West
Optional(Swift_枚举.(testRawValues () -> ()).(Planet #1).uranus)
Optional(Swift_枚举.(testRawValues () -> ()).(Planet #1).uranus)
There isn't a planet at position 9 */
}

枚举循环

//枚举循环
func testRecursiveEnumerations() {
//indirect循环关键字
// enum ArithmeticExpression {
// case Number(Int)
// indirect case Addition(ArithmeticExpression, ArithmeticExpression)
// indirect case Multiplication(ArithmeticExpression, ArithmeticExpression)
// } // 可将indirect写到枚举前
indirect enum ArithmeticExpression {
case number(Int) // 值
case addition(ArithmeticExpression, ArithmeticExpression) // 加
case multiplication(ArithmeticExpression, ArithmeticExpression) // 乘
} // 函数使用
func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case .number(let value):
return value
case .addition(let left, let right):
return evaluate(left) + evaluate(right)
case .multiplication(let left, let right):
return evaluate(left) * evaluate(right)
}
} // evaluate (5 + 4) * 2
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
print(evaluate(product)) /* print 18 */
}

Swift_枚举的更多相关文章

  1. swift_枚举 | 可为空类型 | 枚举关联值 | 枚举递归 | 树的概念

    ***************可为空的类型 var demo2 :we_demo = nil 上面这个代码串的语法是错的 为什么呢, 在Swift中,所有的类型定义出来的属性的默认值都不可以是nil ...

  2. 学习swift从青铜到王者之swift枚举07

    空枚举 //空枚举 enum SomeEnumeration { // enumeration definition goes here } 枚举基本类型 //枚举基本类型 enum CompassP ...

  3. Swift_错误处理

    Swift_错误处理 点击查看源码 //错误处理 func test() { //错误枚举 需ErrorType协议 enum ErrorEnum: Error { case `default` // ...

  4. Swift_初始化

    #Swift_初始化 点击查看源码 初始化结构体 //初始化结构体 func testInitStruct() { //结构体 类中默认方法 struct Size { //宽 var width = ...

  5. Swift_方法

    Swift_方法 点击查看源码 ///方法 class Methods: NSObject { func test() { // self.testInstanceMethods() //实例方法 s ...

  6. Swift_类和结构体

    Swift_类和结构体 点击查看源码 struct Resolution { var width = 0 var height = 0 } class VideoMode { var resoluti ...

  7. Swift enum(枚举)使用范例

    //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...

  8. 编写高质量代码:改善Java程序的151个建议(第6章:枚举和注解___建议88~92)

    建议88:用枚举实现工厂方法模式更简洁 工厂方法模式(Factory Method Pattern)是" 创建对象的接口,让子类决定实例化哪一个类,并使一个类的实例化延迟到其它子类" ...

  9. Objective-C枚举的几种定义方式与使用

    假设我们需要表示网络连接状态,可以用下列枚举表示: enum CSConnectionState { CSConnectionStateDisconnected, CSConnectionStateC ...

随机推荐

  1. sass语法一(变量篇)

    文件后缀名 sass有两种后缀名的文件:一种后缀名为sass,不使用大括号和分号:另一种是我们这里使用的scss文件,这种和我们平时使用的css文件格式差不多,使用大括号和分号. //后缀名为sass ...

  2. 数据结构----线性表顺序和链式结构的使用(c)

    PS:在学习数据结构之前,我相信很多博友也都学习过一些语言,比如说java,c语言,c++,web等,我们之前用的一些方法大都是封装好的,就java而言,里面使用了大量的封装好的方法,一些算法也大都写 ...

  3. Android学习——Service(一)

    这篇博文来介绍Android另一个十分重要的组件,Service.Service和Activity很类似,区别在于它运行在后台,不可见且没有界面.Service的优先级高于Activity,当系统负载 ...

  4. django模板报错:Requested setting TEMPLATE_DEBUG, but settings are not configured. You must either define

    转自:http://blog.csdn.net/xiaowanggedege/article/details/8651236 django模板报错: Requested setting TEMPLAT ...

  5. 并发包Semaphore实现信号灯

    /** * * @描述: Semaphore实现信号灯 . * Semaphore可以维护当前访问自身的线程个数,并提供了同步机制,使用Semaphore可以控制同时访问资源的线程个数,例如实现一个文 ...

  6. PPTP has become obsolete

    https://www.ovpn.com/en/blog/pptp-has-become-obsolete/ PPTP has become obsolete What is PPTP? PPTP s ...

  7. June 25th 2017 Week 26th Sunday

    There is always that one song that brings back old memories. 总有那么一首歌,让你想起那些旧的回忆. There are seveal so ...

  8. January 26 2017 Week 4 Thursday

    Wasting time is robbing yourself. 浪费时间就是掠夺自己. Wasting time is not only robbing yourself, moreover, i ...

  9. C#检验IIS版本、SQL Server版本、SilverLight版本

    之前做一个小项目,使用C#检验这些软件的版本,到处找了一些代码,也能作用,记录一下,以防以后用到. 一.检验IIS版本 public static bool checkIIS(string destV ...

  10. MATLAB入门学习(七)

    开始,线性代数和微积分了,不怕.不怕. 背命令就行了... 线性代数 解线性方程组: Ax=b A是系数矩阵,x未知数,b是列向量 如果有唯一解,直接x=b\A 第二 B=null(A,'r')求Ax ...