swift之枚举

230 阅读1分钟

OC与Swift枚举区别

OC只能玩Int但是swift玩的挺多,

  • 整型(Integer)
  • 浮点数(Float Point)
  • 字符串(String)
  • 布尔类型(Boolean)
enum Area: String {
    case DG = "dongguan"
    case GZ = "guangzhou"
    case SZ = "shenzhen"
}

Swift枚举还可以嵌套

enum Area {
    enum DongGuan {
        case NanCheng
        case DongCheng
    }
    
    enum GuangZhou {
        case TianHe
        case CheBei
    }
}

print(Area.DongGuan.DongCheng)

Swift枚举可以关联值

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

let trade = Trade.Buy(stock: "003100", amount: 100)

switch trade {
case .Buy(let stock,let amount):
    
    print("stock:(stock),amount:(amount)")
    
case .Sell(let stock,let amount):
    print("stock:(stock),amount:(amount)")
default:
    ()
}

Swift枚举可以添加方法和属性

enum Device {
   case iPad, iPhone, AppleTV, AppleWatch
   func introduced() -> String {
       
       switch self {
       case .iPad: return "iPad"
       case .iPhone: return "iPhone"
       case .AppleWatch: return "AppleWatch"
       case .AppleTV: return "AppleTV"
       }
   }
}

print(Device.iPhone.introduced())

Swift枚举可以使用协议

protocol CustomStringConvertible {
  var description: String { get }
}
enum Trade :CustomStringConvertible{
    case Buy(stock:String,amount:Int)
    case Sell(stock:String,amount:Int)
    
    var description: String {
        
        switch self {
        case .Buy(_, _):
            return "Buy"
            
        case .Sell(_, _):
            return "Sell"
        }
    }
}

print(Trade.Buy(stock: "003100", amount: 100).description)

Swift枚举可以使用扩展

enum Device {
    case iPad, iPhone, AppleTV, AppleWatch
    
}

extension Device: CustomStringConvertible{
    
    func introduced() -> String {
        
        switch self {
        case .iPad: return "iPad"
        case .iPhone: return "iPhone"
        case .AppleWatch: return "AppleWatch"
        case .AppleTV: return "AppleTV"
        }
    }
 
    var description: String {
        
        switch self {
        case .iPad: return "iPad"
        case .iPhone: return "iPhone"
        case .AppleWatch: return "AppleWatch"
        case .AppleTV: return "AppleTV"
        }
    }
}

print(Device.AppleTV.description)

print(Device.iPhone.introduced())

Swift枚举可以使用泛型

enum Rubbish<T> {
    
    case price(T)
    
    func getPrice() -> T {
        
        switch self {
        case .price(let value):
            return value
        }
        
    }
}

print(Rubbish<Int>.price(100).getPrice())