//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

enum Movement {
case Left
case Right
case Top
case Bottom
} let aMovement = Movement.Left switch aMovement {
case .Left:
print("left")
default:
print("Unknow")
} if case .Left = aMovement {
print("Left")
} if .Left == aMovement {
print("Left")
} enum Season: Int {
case Spring = 0
case Summer = 1
case Autumn = 2
case Winter = 3
} enum House: String {
case ZhangSan = "I am zhangsan"
case LiSi = "I am lisi"
} let zs = House.ZhangSan
print(zs.rawValue) enum Constants: Double {
case π = 3.14159
case e = 2.71828
case φ = 1.61803398874
case λ = 1.30357
} let pai = Constants.π
print(pai.rawValue) enum CompassPoint: String {
case North, South, East, West
} let n = CompassPoint.North
print(n.rawValue) let s = CompassPoint(rawValue: "South"); enum VNodeFlags : UInt32 {
case Delete = 0x00000001
case Write = 0x00000002
case Extended = 0x00000004
case Attrib = 0x00000008
case Link = 0x00000010
case Rename = 0x00000020
case Revoke = 0x00000040
case None = 0x00000080
} enum Character { enum Weapon {
case Bow
case Sword
case Lance
case Dagger
} enum Helmet {
case Wooden
case Iron
case Diamond
} case Thief
case Warrior
case Knight
} let character = Character.Thief
let weapon = Character.Weapon.Bow
let helmet = Character.Helmet.Iron struct Scharacter {
enum CharacterType {
case Thief
case Warrior
case Knight
} enum Weapon {
case Bow
case Sword
case Lance
case Dagger
} let type: CharacterType
let weapon: Weapon
} let sc = Scharacter(type: .Thief, weapon: .Bow)
print(sc.type) enum Trade {
case Buy(stock: String, amount: Int)
case Sell(stock: String, amount: Int)
} let trade = Trade.Buy(stock: "Car", amount: 100)
if case let Trade.Buy(stock, amount) = trade {
print("buy \(amount) of \(stock)")
} enum Trade0 {
case Buy(String, Int)
case Sell(String, Int)
} let trade0 = Trade0.Buy("Car0", 100)
if case let Trade0.Buy(stock, amount) = trade0 {
print("buy \(amount) of \(stock)")
} enum Wearable {
enum Weight: Int {
case Light = 2
} enum Armor: Int {
case Light = 2
} case Helmet(weight: Weight, armor: Armor) func attributes() -> (weight: Int, armor: Int) {
switch self {
case .Helmet(let w, let a):
return (weight: w.rawValue * 2, armor: a.rawValue * 4) }
}
} let test = Wearable.Helmet(weight: .Light, armor: .Light).attributes()
print(test) enum Device {
case iPad, iPhone, AppleTV, AppleWatch
func introduced() -> String {
switch self {
case .AppleTV: return "\(self) was introduced 2006"
case .iPhone: return "\(self) was introduced 2007"
case .iPad: return "\(self) was introduced 2010"
case .AppleWatch: return "\(self) was introduced 2014"
}
}
}
print (Device.iPhone.introduced()) enum Device1 {
case iPad, iPhone
var year: Int {
switch self {
case .iPad:
return 2010
case .iPhone:
return 2007
}
}
} let iPhone = Device1.iPhone
print(iPhone.year) enum Device2 {
case AppleWatch static func fromSlang(term: String) -> Device2? {
if term == "iWatch" {
return .AppleWatch
}
return nil
}
} print(Device2.fromSlang(term: "iWatch") ?? "nil") enum TriStateSwitch {
case Off, Low, High mutating func next() {
switch self {
case .Off:
self = .Low
case .Low:
self = .High
case .High:
self = .Off
}
}
} var state = TriStateSwitch.Low // 必须使用var
state.next()
state.next() protocol CustomStringConvertible {
var description: String { get }
} enum Trade1: CustomStringConvertible {
case Buy, Sell
var description: String {
switch self {
case .Buy:
return "We're buying something"
case .Sell:
return "We're selling something"
}
}
} let t1 = Trade1.Buy.description protocol AccountCompatible {
var remainingFunds: Int { get }
mutating func addFunds(amount: Int) throws
mutating func removeFunds(amount: Int) throws
} enum Account {
case Empty
case Funds(remaining: Int) enum ErrorInfo: Error {
case OverDraft(amount: Int)
} var remainingFunds: Int {
switch self {
case .Empty:
return 0
case .Funds(let remaining):
return remaining
}
}
} extension Account: AccountCompatible {
mutating func addFunds(amount: Int) throws {
var newAmount = amount
if case let .Funds(remaining) = self {
newAmount += remaining
} if newAmount < 0 {
throw Account.ErrorInfo.OverDraft(amount: newAmount)
}else if newAmount == 0 {
self = .Empty
}else {
self = .Funds(remaining: newAmount)
}
} mutating func removeFunds(amount: Int) throws {
try self.addFunds(amount: amount * -1)
}
} var account = Account.Funds(remaining: 20)
try? account.addFunds(amount: 20)
print("add: ", account.remainingFunds)
try? account.removeFunds(amount: 15)
print ("remove 1: ", account.remainingFunds) do {
try account.removeFunds(amount: 55)
}catch (let errorInfo) {
print(errorInfo)
}
print ("remove 2: ", try? account.removeFunds(amount: 55))

来源:Swift 中枚举高级用法及实践

Advanced & Practical Enum usage in Swift

Swift enum(枚举)使用范例的更多相关文章

  1. Swift Enum 枚举

    前言 枚举是一种自定义的数据类型,在 Swift 中枚举类型拥有相当高的自由度.在 Swift 语言中枚举是一级类型,它拥有在其他语言中只有类才拥有的一些特性,比如实例方法,实例构造器等. 枚举声明的 ...

  2. iOS - Swift Enum 枚举

    1.Enum 的创建 1.1 标准定义 枚举的定义 enum CompassPoint { case North case South case East case West } enum Plane ...

  3. swift 的枚举、结构体、类

    一.Swift的枚举 枚举是一系相关联的值定义的一个公共的组类型,同时能够让你在编程的时候在类型安全的情况下去使用这些值.Swift中的枚举比OC中的枚举强大得多, 因为Swift中的枚举是一等类型, ...

  4. swift学习——枚举

    swift枚举 1. 枚举基本语法 enum Method { case Add case Sub case Mul case Div } 也可以使用一种更简单的写法 enum Method1{ ca ...

  5. Swift 中枚举

    Swift 中枚举高级用法及实践 字数11017 阅读479 评论0 喜欢20 title: "Swift 中枚举高级用法及实践"date: 2015-11-20tags: [AP ...

  6. c# (ENUM)枚举组合类型的谷歌序列化Protobuf

    c# (ENUM)枚举组合类型的谷歌序列化Protobuf,必须在序列化/反序列化时加上下面: RuntimeTypeModel.Default[typeof(Alarm)].EnumPassthru ...

  7. C#将Enum枚举映射到文本字符串

    介绍 当将以前的C代码移植到C#中时,我快发疯了,因为有很多的数组需要将常量映射到字符串.当我在寻找一个C#的方法来完成的时候,我发现了一个自定义属性和映射的方法. 如何使用代码? 对每一个enum枚 ...

  8. MVC3不能正确识别JSON中的Enum枚举值

    一.背景 在MVC3项目里,如果Action的参数中有Enum枚举作为对象属性的话,使用POST方法提交过来的JSON数据中的枚举值却无法正确被识别对应的枚举值. 二.Demo演示 为了说明问题,我使 ...

  9. 161208、Java enum 枚举还可以这么用

    在大部分编程语言中,枚举类型都会是一种常用而又必不可少的数据类型,Java中当然也不会例外.然而,Java中的Enum枚举类型却有着许多你意想不到的用法,下面让我们一起来看看. 先来看一段代码示例: ...

随机推荐

  1. 学习AOP之透过Spring的Ioc理解Advisor

    花了几天时间来学习Spring,突然明白一个问题,就是看书不能让人理解Spring,一方面要结合使用场景,另一方面要阅读源代码,这种方式理解起来事半功倍.那看书有什么用呢?主要还是扩展视野,毕竟书是别 ...

  2. JAVA for mac 的学习之路

    要学习一门新技术,首先得下载相关的工具. 一 . 下载相关工具 1. 下载 jdk formac 下载地址为:http://www.oracle.com/technetwork/java/javase ...

  3. html与html5

    HTML 是一种在 Web 上使用的通用标记语言.HTML 允许你格式化文本,添加图片,创建链接.输入表单.框架和表格等等,并可将之存为文本文件,浏览器即可读取和显示.HTML 的关键是标签,其作用是 ...

  4. AJAX实现登录界面

    使用php跳转界面和AJAX都可实现登录界面的跳转的登录失败对的提醒.但是,php跳转的方式 需要额外加载其他界面,用户体验差.AJAX可实现当前页面只刷新需要的数据,不对当前网页进行 重新加载或者是 ...

  5. VS2015使用scanf报错的解决方案

    1.在程序最前面加: #define _CRT_SECURE_NO_DEPRECATE 2.在程序最前面加: #pragma warning(disable:4996) 3.把scanf改为scanf ...

  6. JavaScript学习笔记(一)——延迟对象、跨域、模板引擎、弹出层、AJAX示例

    一.AJAX示例 AJAX全称为“Asynchronous JavaScript And XML”(异步JavaScript和XML) 是指一种创建交互式网页应用的开发技术.改善用户体验,实现无刷新效 ...

  7. Eclipse出现"Running Android Lint has encountered a problem"解决方案

    安装eclipse for android 时候的错误记录,转载自:http://blog.csdn.net/chenyufeng1991/article/details/47442555 (1)打开 ...

  8. Java虚拟机 JVM

    finalize();(不建议使用,代价高,不确定性大) 如果你在一个类中覆写了finalize()方法, 那么你可以在第一次被GC的时候,挽救一个你想挽救的对象,让其不被回收,但只能挽救一次. GC ...

  9. 解决:win10_x64 VMware Workstation and Hyper-V are not compatible. Remove the Hyper-V role from the system before running VMware Workstation

    bcdedit /set hypervisorlaunchtype off A reboot of of the Windows OS is necessary  必须重启才能生效   To enab ...

  10. SpringMvc中的数据校验

    SpringMvc中的数据校验 Hibernate校验框架中提供了很多注解的校验,如下: 注解 运行时检查 @AssertFalse 被注解的元素必须为false @AssertTrue 被注解的元素 ...