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枚举类型却有着许多你意想不到的用法,下面让我们一起来看看. 先来看一段代码示例: ...
随机推荐
- 从Script到Code Blocks、Code Behind到MVC、MVP、MVVM
刚过去的周五(3-14)例行地主持了技术会议,主题正好是<UI层的设计模式——从Script.Code Behind到MVC.MVP.MVVM>,是前一天晚上才定的,中午花了半小时准备了下 ...
- Android GridView 通过seletor 设置状态和默认状态
Android中可以通过selector控制GridView Item 的状态,而省去使用代码控制 GridView View Selector Xml文件 <?xml version=&quo ...
- [WCF]缺少一行代码引发的血案
这是今天作项目支持的发现的一个关于WCF的问题,虽然最终我只是添加了一行代码就解决了这个问题,但是整个纠错过程是痛苦的,甚至最终发现这个问题都具有偶然性.具体来说,这是一个关于如何自动为服务接口(契约 ...
- PHP之Memcache缓存详解
Mem:memory缩写(内存):内存缓存 1. 断电或者重启服务器内存数据即消失,即临时数据: Memcache默认端口:11211 存入方式:key=>>value ...
- 在centos7中添加一个新用户,并授权
前言 笔记本装了一个centos,想要让别人也可以登录访问,用自己的账号确实不太好,于是准备新建一个用户给他. 创建新用户 创建一个用户名为:zhangbiao [root@localhost ~]# ...
- 关于sql server 2005存储过程的写法
打开数据库的SQL Server Managerment Studio---->数据库----->打开数据库会看见"可编程行"------->打开有存储过程--- ...
- MongoDB学习笔记~对集合属性的操作
回到目录 $unset清除元素 请注意在单个数组元素上使用$unset的结果可能与你设想的不一样.其结果只是将元素的值设置为null,而非删除整个元素.要想彻底删除某个数组元素,可以用$pull 和$ ...
- TCP/IP之TCP_NODELAY与TCP_CORK
TCP/IP之Nagle算法与40ms延迟提到了Nagle 算法.这样虽然提高了网络吞吐量,但是实时性却降低了,在一些交互性很强的应用程序来说是不允许的,使用TCP_NODELAY选项可以禁止Nagl ...
- 微软.Net 社区虚拟大会 -- 首日重点(dotnetConf 2016)
6月7日--9日,为期三天的微软.NET社区虚拟大会正式在 Channel9 上召开. 在 Scott Hunter, Miguel de Icaza (Xamarin CTO) , ScottHan ...
- DIP原则、IoC以及DI
一.DIP原则 高层模块不应该依赖于底层模块,二者都应该依赖于抽象. 抽象不应该依赖于细节,细节应该依赖于抽象. 该原则理解起来稍微有点抽象,我们可以将该原则通俗的理解为:"依赖于抽象&qu ...