枚举

枚举

  • 一般情况
enum Sorce {
    case y
    case x
}
let direction: Sorce = .x
  结果:
 x
  • rawValue
 enum Direction: String {
          case north = "N"
          case south = "S"
          case east  = "E"
          case west  = "W"
}
print(Direction.north, Direction.north.rawValue)

结果:

north N

更加复杂一点

enum Direction: String {
    case north
    case sourth = "S"
    case east  = "E"
    case west  = "W"
    
}
let Move = Direction.north
switch Move {
    case .north: print("north")
    case .sourth: print("sourth")
    case .east: print("east")
    case .west: print("west")
}
print(Direction.north, Direction.north.rawValue, Direction.sourth, Direction.sourth.rawValue)

总结

enum Direction: String {
	case north, south, east, west
 }
  • 关联值
enum Sorce {
    case points(Int)
    case grade(Character)
}

let sorceA: Sorce = .points(15)
let sorceB: Sorce = .grade("A")
print(sorceA, sorceB)
switch sorceA {
    case let .points(point): print(point)
    case let .grade(char): print(char)
}

结果:

points(15) grade("A")
15

递归枚举

indirect enum ArithExpr {
    case number(Int)
    case sum(ArithExpr, ArithExpr)
    case difference(ArithExpr, ArithExpr)
}
func sumVale(_ expression: ArithExpr) -> Int {
    switch expression {
    case let .number(value):
        return value
    case let .sum(value1, value2):
        return sumVale(value2) + sumVale(value1)
    case let .difference(left, right):
        return  sumVale(left) - sumVale(right)
    }
}

let value1 = ArithExpr.number(10)
let value2 = ArithExpr.number(20)
let A = sumVale(ArithExpr.sum(value1, value2))
let B = sumVale(ArithExpr.difference(value2, value1))
print(A, B, sumVale(value1), sumVale(value2), value1, value2)

结果
30 10 10 20 number(10) number(20)

@inline

//永远不会被内联 (即使开启了编译器优化)
@inline(never) fun test() {

}

//开启编译器优化后, 即使代码很长, 也会被内联 (递归, 动态派发除外)
@inline(_always) func test() {

}

posted @ 2020-08-09 23:26  千面客  阅读(108)  评论(0编辑  收藏  举报