Swift enum(枚举)使用范例
//: 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(枚举)使用范例的更多相关文章
- Swift Enum 枚举
前言 枚举是一种自定义的数据类型,在 Swift 中枚举类型拥有相当高的自由度.在 Swift 语言中枚举是一级类型,它拥有在其他语言中只有类才拥有的一些特性,比如实例方法,实例构造器等. 枚举声明的 ...
- iOS - Swift Enum 枚举
1.Enum 的创建 1.1 标准定义 枚举的定义 enum CompassPoint { case North case South case East case West } enum Plane ...
- swift 的枚举、结构体、类
一.Swift的枚举 枚举是一系相关联的值定义的一个公共的组类型,同时能够让你在编程的时候在类型安全的情况下去使用这些值.Swift中的枚举比OC中的枚举强大得多, 因为Swift中的枚举是一等类型, ...
- swift学习——枚举
swift枚举 1. 枚举基本语法 enum Method { case Add case Sub case Mul case Div } 也可以使用一种更简单的写法 enum Method1{ ca ...
- Swift 中枚举
Swift 中枚举高级用法及实践 字数11017 阅读479 评论0 喜欢20 title: "Swift 中枚举高级用法及实践"date: 2015-11-20tags: [AP ...
- c# (ENUM)枚举组合类型的谷歌序列化Protobuf
c# (ENUM)枚举组合类型的谷歌序列化Protobuf,必须在序列化/反序列化时加上下面: RuntimeTypeModel.Default[typeof(Alarm)].EnumPassthru ...
- C#将Enum枚举映射到文本字符串
介绍 当将以前的C代码移植到C#中时,我快发疯了,因为有很多的数组需要将常量映射到字符串.当我在寻找一个C#的方法来完成的时候,我发现了一个自定义属性和映射的方法. 如何使用代码? 对每一个enum枚 ...
- MVC3不能正确识别JSON中的Enum枚举值
一.背景 在MVC3项目里,如果Action的参数中有Enum枚举作为对象属性的话,使用POST方法提交过来的JSON数据中的枚举值却无法正确被识别对应的枚举值. 二.Demo演示 为了说明问题,我使 ...
- 161208、Java enum 枚举还可以这么用
在大部分编程语言中,枚举类型都会是一种常用而又必不可少的数据类型,Java中当然也不会例外.然而,Java中的Enum枚举类型却有着许多你意想不到的用法,下面让我们一起来看看. 先来看一段代码示例: ...
随机推荐
- 深入理解C#
简单认识.NET框架 (1)首先我们得知道 .NET框架具有两个主要组件:公共语言进行时CLR(Common Language Runtime)和框架类库FCL(Framework Class ...
- Node.js:Buffer浅谈
Javascript在客户端对于unicode编码的数据操作支持非常友好,但是对二进制数据的处理就不尽人意.Node.js为了能够处理二进制数据或非unicode编码的数据,便设计了Buffer类,该 ...
- [原] KVM 虚拟化原理探究(3)— CPU 虚拟化
KVM 虚拟化原理探究(3)- CPU 虚拟化 标签(空格分隔): KVM [TOC] CPU 虚拟化简介 上一篇文章笼统的介绍了一个虚拟机的诞生过程,从demo中也可以看到,运行一个虚拟机再也不需要 ...
- 【转】java通用URL接口地址调用方式GET和POST方式
java通用URL接口地址调用方式GET和POST方式,包括建立请求和设置请求头部信息等等......... import java.io.ByteArrayOutputStream; import ...
- java中易错点(二)
java,exe是java虚拟机 javadoc.exe用来制作java文档 jdb.exe是java的调试器 javaprof,exe是剖析工具 解析一: sleep是线程类(Thread)的方法, ...
- css3制作旋转动画
现在的css3真是强大,之前很多动画都是用jq来实现,但是css3制作的动画要比jq实现起来简单很多,今天呢,我自己也写了一个css旋转动画和大家分享.效果如下面的图片 思路:1.制作之前呢,我们先来 ...
- webpack学习总结
前言 在还未接触webpack,就有几个疑问: 1. webpack本质上是什么? 2. 跟异步模块加载有关系吗? 3. 可否生成多个文件,一定是一个? 4. 被引用的文件有其他异步加载模块怎么办? ...
- 超全面的.NET GDI+图形图像编程教程
本篇主题内容是.NET GDI+图形图像编程系列的教程,不要被这个滚动条吓到,为了查找方便,我没有分开写,上面加了目录了,而且很多都是源码和图片~ (*^_^*) 本人也为了学习深刻,另一方面也是为了 ...
- 洛谷P1547 Out of Hay
题目背景 奶牛爱干草 题目描述 Bessie 计划调查N (2 <= N <= 2,000)个农场的干草情况,它从1号农场出发.农场之间总共有M (1 <= M <= 10,0 ...
- 【流量劫持】沉默中的狂怒 —— Cookie 大喷发
精简版:http://www.cnblogs.com/index-html/p/mitm-cookie-crack.html 前言 上一篇文章 讲解了如何借助前端技术,打造一个比 SSLStrip 更 ...