最近在看Alamofire的源码,但是Alamofire中使用了大量的枚举,这货打开的方式跟OC不一样,所以从简单的枚举整理开始
1.普通写法
enum Direction {
case east
case west
case south
case north
}
//关联值类型写法 Int 代表枚举值的类型 关联值类型可为 Int , String ,Boolen
enum Direction : Int {
case east
case west
case south
case north
}
复制代码
2.简单写法
enum Direction {
case east, west,south, north
}
//如果关联值类型为Int,这枚举默认值分别为 0 1 2 3 如果指定第一个为具体数值后面一次+1
enum Direction : Int {
case east = 1, west,south, north
}
//如果关联值类型为String 在没有指定的情况下 默认为当前case的名称
enum Direction : String {
case east , west,south, north
}
//如下可指定枚举的具体值
enum Direction : String {
case east = "zhangsan", west = "lisi" ,south = "wangwu", north = "zhaoliu"
}
复制代码
3.初始化
let dire1 = Direction.north
//错误写法
let dire2 = Direction()
//指定关联值类型 rawValue为初始值,rawValue必须存在
let dire3 = Direction.init(rawValue: "zhangsan")
let dire4 = Direction.init(rawValue: 1)
复制代码
4.枚举嵌套
enum Direction : Int {
enum vertical : Int {
case top,middle,bottom
}
enum horizontal {
case left ,middle , bottom
}
case east
case west
case south
case north
}
let dire1 = Direction.init(rawValue: 1)
print(dire1!)//west
let dire2 = Direction.horizontal.left
print(dire2)//left
let dire3 = Direction.vertical.init(rawValue: 0)
print(dire3!)//top
复制代码
5.包含枚举
class ViewController: UIViewController {
enum Human {
case man, woman
}
let human : Human? = .man
override func viewDidLoad() {
super.viewDidLoad()
}
}
struct World {
enum Human {
case man, woman
}
var human : Human?
var plants : String
}
复制代码
6.关联值
//number作为标签可以不写
enum Fruit {
case Apple(number : Int)
case banana( number: Int)
}
func buyFruit(type: Fruit) {
}
//调用 语义明了 买水果(苹果10个)
buyFruit(type: .Apple(number: 10))
//这样也可以
let fruit = Fruit.Apple(number: 10)
buyFruit(type: fruit)
复制代码
7.枚举中使用方法,静态方法,属性(这些都是为了枚举服务)
enum Direction {
enum vertical : Int {
case top,middle,bottom
}
enum horizontal {
case left ,middle , bottom
}
case east
case west
case south
case north( distance : Int)//参数
//方法
func goLong(distance : Int) -> String {
switch self {
case .east:
return "east:\(distance)"
default:
return "back"
}
}
static func directioned(type : Int) ->Direction{//类似类方法
switch type {
case 0:
return .east
case 1:
return .west
case 2:
return .south
default:
return .east
}
}
//属性
var trueDirection : Bool {
switch self {
case .east:
return true
default:
return false
}
}
}
let dire = Direction.east
print(dire)
print(dire.goLong(distance: 1000))
print(dire.trueDirection)
复制代码