swift-枚举

2018-03-22  本文已影响8人  malgee

swift中的枚举不仅能表示整型的枚举, 还可以表示其他类型的枚举(字符串枚举)

可选性的实质就是枚举类型,一个值是nil, 一个值就是定义的类型

// 通过添加:Int 定义枚举是整型的枚举
enum Month: Int {
    case January
    case February
    case March
    case April
    case May
    case June
    case July
    case August
    case September
    case October
    case November
    case December
}

// .June 前面知道是枚举类型, 所以可以省略前面的枚举名称,直接 . 出来后面的枚举值
let currentMonth: Month = Month.June

let currentMonth2: Month = .June

// 整型的枚举 原始值 rawValue
Month(rawValue: 10)  // November
// 字符串类型的枚举, 后面的值可以不写, 默认就是枚举名称, 也可以写出来
enum Language: String {

    case Swift = "swift"
    case ObjectiveC = "Objective-C"
    case HTML
    case CSS
}

let myLanguage: Language = .ObjectiveC

// .rawValue 获取枚举的值
print(myLanguage.rawValue)  // Objective-C
// associate value 相关联的枚举, 可以存放不同类型

enum ATMStatus {

    case Success(Int)
    case Error(String)
}

var balance = 1000

func draw(amount: Int) -> ATMStatus {

    if balance >= amount {
        
        balance -= amount
        
        return .Success(balance)
    }
    else {
    
    return .Error("余额不足")
    }
}

let myStatus = draw(amount: 100)

switch myStatus {
    case let .Success(newValue):
        print("还剩余 \(newValue) 元")
        
    case let .Error(msg):
        print("error: \(msg)")
}

输出: 还剩余 900 元

对于枚举的值的不关心, 可以这么写:
switch myStatus {
case .Success:
    print("成功")
    
case .Error:
    print("失败")  
}

// 补充:

// 多个参数的枚举
enum Shape {
    case Square(side: Double)
    case Rectangle(width: Double, height: Double)
    case Circle(centerX: Double, centerY: Double, radius: Double)
    case Point
}

// 这里给枚举传参赋值
let square = Shape.Square(side: 10)

let Rectangle = Shape.Rectangle(width: 10, height: 30)

let Circle = Shape.Circle(centerX: 0, centerY: 0, radius: 10)

let Point = Shape.Point


func area(shape: Shape) -> Double {

    switch shape {
    case let .Square(side: side):
        
        return side * side
        
    case let .Rectangle(width: width, height: height):
        
        return width * height
        
    case let .Circle(_, _, radius: radius):
        
        return M_PI * radius * radius

    case .Point:
        
        return 0
    }

}
// 计算面积
area(shape: square)
area(shape: Rectangle)
area(shape: Circle)
area(shape: Point)

可选性的实质就是枚举

可选性有2个枚举值: `none`、 `some(xx)`
 /// The absence of a value.
    ///
    /// In code, the absence of a value is typically written using the `nil`
    /// literal rather than the explicit `.none` enumeration case.
    case none

    /// The presence of a value, stored as `Wrapped`.
    case some(Wrapped)
`

// 定义一个可选性
var testOption: Optional<String> = Optional.some("malgee")

testOption = .none

switch testOption {
case .none:
    print("nil")
case let .some(string):
    
    print(string)
}

上一篇下一篇

猜你喜欢

热点阅读