In view of the department meeting discussion yesterday, I found some friends still have some doubts about the usage of enumeration, so I write this article to introduce the usage of enumeration under Swift. The basic enumeration type is:

enum Movement {
    case letf
    case right
    case top
    case bottom
}
Copy the code

Here we define a simple enumeration of directions with up, down, left and right cases. So what can we do? 1. You can iterate through his enumeration:

let aMovement = Movement.left

switch aMovement {
case .left:
    print("Left")
default:()
    
}
Copy the code

2. You can compare scenarios:

if aMovement == .left {
    print("Left")}Copy the code

OC can only play Int, it can play Int:

  • Integer (Integer)
  • Float Point
  • String (String)
  • Boolean type (Boolean)
enum Movement:Int {
    case left = 0
    case right = 1
    case top = 2
    case bottom = 3
}

enum Area: String {
    case DG = "dongguan"
    case GZ = "guangzhou"
    case SZ = "shenzhen"
}
Copy the code

However, if you want to play with a custom class association type, it won’t work, but it will work. If you want the value of an enumerated case, print(area.dg. rawValue) and call rawValue directly. Note, however, that if you use rawValue to construct an enumeration object, it may not be in any of the scenarios because its return value is optional.

### nested enumeration

enum Area {
    enum DongGuan {
        case NanCheng
        case DongCheng
    }
    
    enum GuangZhou {
        case TianHe
        case CheBei}}print(Area.DongGuan.DongCheng)
Copy the code

On the code, at a glance, how to tune, see directly, ha ha ~~~

### associative value

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: ()}Copy the code

You see, in fact, is the enumeration of case can pass the value, do not look down on this function, in OC, to write such code, trouble to go.

### method and attribute code first:

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

Very clearly, we’ve defined an enumeration of devices, iPad, iPhone, AppleTV, AppleWatch, and an introduction method. The introduced method here, you can think of the enumeration as a class, the introduced method as a member method, Device. IPhone is an instance of a Device, and cases are its properties. Ok, so if you have this object, Device. Device has an anonymous property inside it, now set that property to iPhone. Well, the switch Self introduced was actually going through all the scenarios of the anonymous attribute, such as iPad and iPhone, and then returning different values according to different scenarios.

### properties Adding a storage property to an enumeration is not allowed, but you can still create calculated properties. Of course, the content of the calculated property is based on enumeration values or enumeration associations.

enum Device {
  case iPad, iPhone
  var year: Int {
    switch self {
	    case iPhone: return 2007
	    case iPad: return 2010}}}Copy the code

Static method

enum Device {
    case iPad, iPhone, AppleTV.AppleWatch
    func introduced(a) -> String {
        
        switch self {
        case .iPad: return "iPad"
        case .iPhone: return "iPhone"
        case .AppleWatch: return "AppleWatch"
        case .AppleTV: return "AppleTV"}}static func fromSlang(term: String) -> Device? {
        
        if term == "iWatch" {
            
            return .AppleWatch
        }
        return nil}}print(Device.fromSlang(term: "iWatch"))
Copy the code

static func fromSlang(term: String) -> Device? It’s a static method.

Swift also allows you to use Protocols and Protocol extensions in enumerations. The Swift protocol defines an interface or type for other data structures to follow. Enum is certainly no exception. Let’s start with an example from the Swift standard library. CustomStringConvertible is a custom formatted output type for printing purposes.

protocol CustomStringConvertible {
  var description: String { get}}Copy the code

The protocol has only one requirement, which is a String of read-only (getter) type (String). We can easily implement this protocol for enUms.

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)
Copy the code

### Extend enumerations can also be extended. The most obvious use case is to separate the case and method of enumerations so that reading your code can easily and quickly digest the enum content and then move on to the method definition:

enum Device {
    case iPad, iPhone, AppleTV.AppleWatch
    
}
extension Device: CustomStringConvertible{
    
    func introduced(a) -> 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())

Copy the code

# # # generics

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

print(Rubbish<Int>.price(100).getPrice())
Copy the code

Good, basically these, have the word that should complement, beg reply ~~~~~