1. 程式人生 > >Swift 列舉的模式匹配

Swift 列舉的模式匹配

關聯值設定列舉

enum Trade {
    case Buy(stock: String, amount: Int)
    case Sell(stock: String, amount: Int)
}

模式匹配訪問

let trade = Trade.Buy(stock: "APPL", amount: 500)

//值繫結模式
switch trade {
        case .Buy(stock: let name, amount: let count):
            print("\(name)--\(count)")
        default:
            break
}

//當只有一個條件的時候,用switch會顯得冗餘,直接用if case let會使程式碼讀起來更便捷
if case let Trade.Buy(stock, amount) = trade {
    print("buy \(amount) of \(stock)")
}