Come, xiao Ming tell me what is enumeration Xiao Ming: you raise your hand and then? Xiaoming: Did you see my hand lift?Copy the code

 

The basic definition

As the first-class type of Swift, enumeration is a good way to list Swift’s other powerful types

Start by writing out two ways to express enumerations

They are placed in brackets, arranged vertically, and do not interfere with each other

enum SwiftType {
    case protocol
    case enum
    case struct
    case class
    case tuple
    case function
}
Copy the code

Or they can embrace each other in a comma of awe

enum ProgrammingLanguage {
    case protocol, enum, struct, class, tuple, function
}
Copy the code

Master the above types, you can call the wind and rain

So LET me write down enumerations as a beginner

 

Original value rawValue

Swift enumerations are not fixed with a default integer value like OC, there is no top-down, and the raw values are not 0 to 5

Their raw values can also be of other types

enum RawValueType {
    caseplasticcasecharactercasestringcaseFloating-point}Copy the code

But they must have a common type and a unique primitive value

Enumerations like ProgrammingLanguage that do not specify a primitive value type have no primitive values,

Their instances also cannot point rawValue with dot syntax

 

Assign a primitive value type

If we want to get the raw value like OC, we can specify the type

enum ProgrammingLanguage: Int {
    case Swift 
    case OC
    case Python
    case Java
}
Copy the code

Once we give an integer, that means they start at 0 by default

 

The original value of the next enumeration = the original value of the previous enumeration + 1

 

⚠️ only plastic is such a sequence of cumulative oh

var p = ProgrammingLanguage.OC.rawValue

print(p) // Print 1, since Swift defaults to 0Copy the code

Now let’s make some changes

enum ProgrammingLanguage: Int {
    case Swift = 2
    case OC
    case Python = 6
    case Java
}

var p = ProgrammingLanguage.OC.rawValue
print(p) // Prints 3, because Swift is 2print(p1) // Print 7, because Python is 6Copy the code

 

String implicitly primitive value

If we specify that the enumeration type is String, then the rawValues of cases are their stringification

enum Song: String {
    caseSummer wash stonecaseRawValue debugPrint(s) // Prints a string"Summer Gargle stone"
Copy the code

 

RawValue initialization

Enumerations can be initialized with the raw rawValue

Such as

enum Drinking: String {
    case cola
    case sprite
    case orangeJuice
}

var dg = Drinking(rawValue: "cola")

The enumeration doesn't know if the rawValue you passed in exists

Instantiation in this way is a failable constructor, as described below
Copy the code

 

Switch matches the enumerated value

In general, we write enumerations to distinguish between different cases, and just like OC, Switch is our first choice for matching enumerations

There are two kinds of enumeration cases for Swift

// Enumeration of login modes enum LoginWay {case Apple
    case QQ
    case Wechat
    case Weibo
}

let way = LoginWay.Apple
Copy the code

The first is to exhaust everything

* Traverses all of the bracescaseDefult * if missing, and there is no defult will be an error switch way {case .Apple:
    print("apple")
case .QQ:
    print("qq")
case .Wechat:
    print("wechat")
case .Weibo:
    print("weibo"} // Print"apple"
Copy the code

Second: do what they like

* Only show part of what I care aboutcaseDefult represents * instead of displaying all switch way {case .QQ:
    print("qq")
case .Weibo:
    print("weibo")
default:
    print("Other"} // Print"Other"
Copy the code

* associated values

What are associated values?

Let’s look at a chestnut

Enum OnTheWayTime {// Define a different way of working.caseBicycle (Int) // Bicycle with an associated value of IntcaseTaxi (Int) // Taxi of the Int associated valuecaseBus (time: Int) // Bus of the associated value of IntcaseHorse (String) horse} var t = onThewayTime.bicycle (60) //"Instantiate a variable"And associate the member variable bicycle with an Int value of 60Copy the code

If we want to change t, the way we travel

In the case that the type of t is determined, we can dispenses with the enumeration name and just.

t = .taxi(30)

 

Let’s go to Switch and walk through the enumeration to see how the associated values are used

switch t {
case .bicycle(let bic):
    print("Cycling to work takes \(bic) minutes")
case .taxi(let ti):
    print("It takes \(ti) minutes to get a taxi to work")
case .bus(time: let bs):
    print("It takes \(BS) minutes to get to work by bus")
case .horse(let str):
    print("Ride a horse \(STR)"} can be used to extract correlation values"let / var"The modifier is generated by value binding"Local variable"with"Associated value"connectedCopy the code

 

Change t and iterate, t can change at will

T =.horse(” very long “)

Print: Riding a horse takes a long time

 

Optional associated values

Optional is a common enumeration, and its member value.some is also associated with a value

var age: Int?
age = 17

switch age {
case .none:
  print("The age for nil")
case .some(let value):
  print("The value of age is: \(value)"} // Print: age is 17Copy the code

 

The problem

Does the member of the associated value have rawValue?

The answer is no

RawValue complies with the RawRepresentable protocol, which associates rawValue with associatedType, which defines the type of association used in the protocol. Although the association type is uncertain, But they are unified.

Enumerations with associated values are not of uniform type, so rawValue cannot be used

 

conclusion

  • We can think of the correlation value as a variable,The value of the member after the association is variable
  • The associated value is different from the original value,The value of the original value is fixed from the beginning and cannot be changed  
  • Associated values cannot use the rawValue attribute because they cannot be typed uniformly

 

The construction process of enumeration

Construction process: Ensures that new instances are properly initialized before being used for the first time

In addition to rawValue initialization mentioned above, which is a hidden init, right? In addition to the failable constructor,

We can also customize init that’s not hidden, right? The initializer

enum Drinking: String {
    case cola
    case sprite
    caseorangeJuice init? (str: String) { switch str {case "c":
            self = .cola
        case "s":
            self = .sprite
        case "o":
            self = .orangeJuice
        default:
        returnNil}}} next time you can initialize it either way:let dg = Drinking(rawValue: "cola") / /print(dg!)  cola

let gc  = Drinking(str: "s") / /print(gc!)  sprite
Copy the code

 

The problem

Didn't we just list all the cases, case "C", "s", "O", so we don't have to put a question mark after init? Can you do without defult?

The answer is no

Although our list of cases is exhaustive, there is no guarantee that you will pass in something when you initialize a construct, so it is possible that the construct will fail and the result will be optional, so add? Defult is needed to process cases that do not exist

 

Enumerated properties

Calculate attribute

Here, look at the chestnuts

It’s time for kaifeng

We wrote an enumeration of KFC’s a la carte/combo, and the outside world got the description by calling the instance’s description

enum KFCFood {
    case familyFood(Int)
    case Other(String, String, String)
    
    var description: String {
        switch self {
        case .familyFood(let num):
            return "Today I ate \(num) whole family barrel by myself"
        case let .Other(s1, s2, s3):
            return "Had \(s1) \(s2) and \(s3) for dinner tonight"
        }
    }
}

var k = KFCFood.familyFood(2)
print// TODAY I ate two buckets by myself."Hamburger"."Coke"."French fries")
printI had hamburger, Coke and French fries for dinner todayCopy the code

We define an enumeration of KFC

Store and get description by associating values + calculating properties

 

summary

  • We can’t initialize rawValue because we have an associative value, which means that if we initialize rawValue, that means that all the instances that we get are there,Defult is not needed in switch

case let .Other(s1, s2, s3):

  • If there is more than one correlation value, then we can use it to modify local variablesLet /var comes first

 

Second way of writing extensions and protocols

We can also use Protocols and Protocol extensions.

Tall and tall is there

Protocols and protocol extensions make it easier to separate member values from property/method implementations, making the code naturally easier to read

enum KFCFood {
    case familyFood(Int)
    case Other(String, String, String)
}

protocol EatFood {
    var description: String { get }
}

extension KFCFood: EatFood {
    var description: String {
         switch self {
         case .familyFood(let num):
             return "Today I ate \(num) whole family barrel by myself"
         case let .Other(s1, s2, s3):
             return "Had \(s1) \(s2) and \(s3) for dinner tonight"}}}Copy the code

 

Method of enumeration

We can define methods in enumerations just as we can define methods in classes

enum Song: String {
    case chinese
    case english
    func getName() -> String {
        switch self {
        case .chinese:
            return "chinese"
        case.english:
            return "english"}}}let s  = Song.chinese
print(s.get_name ()) // Print ChineseCopy the code

So what if we want to change our value within the method?

For example, we want to switch between Chinese songs and English songs

Like this

enum Song: String {
    case chinese
    case english
     func getChange() {
        switch self {
        case.chinese: self =.english // change the English song}}# Cannot assign to value: 'self' is immutable
Copy the code

This is where mutating comes in

mutating

Mutating in front of func lets you change your own value in the value type

conclusion

Refer to the link

SwiftGG

If there is any new knowledge, I will add it. All the above are my personal opinions. If there is any mistake, it is the first time to learn Swift.Copy the code