C language enumeration writing method review

Before we look at Swift enumerations, let’s review C’s enumerations:

Enum Enum name {enumeration value 1, enumeration value 2,.... }; <! --> enum Weak{MON, TUE, WED, THU, FRI, SAT, SUN}; --> enum Weak{MON, TUE, WED, THU, FRI, SAT, SUN}; <! // If no enumeration default value is set, the first enumeration member defaults to integer 0, and then repeats. If we want to change the value, Enum Weak{MON = 1, TUE, WED, THU, FRI, SAT, SUN}; <! Weak enum weak {MON = 1, TUE, WED, THU, FRI, SAT, SUN}weak; Enum {MON = 1, TUE, WED, THU, FRI, SAT, SUN}weak;Copy the code

The enumeration analogy in Swift

In SWIFT, enumerations are created as follows. If the enum type is not specified, the default enum is an integer

<! --> enum Weak{case MON case TUE case WED case THU case FRI case SAT case SUN} <! Enum Weak{case MON, TUE, WED, THU, FRI, SAT, SUN} <! Var w: Weak =.monCopy the code

In the appellate code our enumeration type defaults to an integer, which is consistent with C. What if we want to express a String? You can create an enum value by specifying the type of the enum value. The relationship between the enum value and the rawValue rawValue is case enumeration value = rawValue rawValue

/* = The value on the left is an enumeration value, for example, the value on the right is called RawValue in swift, for example, "MON". The relationship between the two is: case enumeration value = RawValue */ enum Weak: String{ case MON = "MON" case TUE = "TUE" case WED = "WED" case THU = "THU" case FRI = "FRI" case SAT = "SAT" case SUN =  "SUN" }Copy the code
  • You can also use it if you don’t want to write a string after the enumeration valueImplicit RawValueDistribution,Implicit RawValue allocationIs based onSwift's type inference mechanism, we use the following firstIntHere’s an example:
<! Int{case MON, tue, WED, thu, fri = 10, sat, sun}Copy the code

By default, the system starts at 0. You can specify frI = 10 during this process, so for sat, the system will add up from the previous case, which is 11.

If this is true only for ints, the same is true for strings.Next we want to distinguish one thing, let’s look at the printout of the following code

enum DayOfWeek:String { case monday, tuesday, wednesday, thursday, friday, saturday, Sunday} print(dayofweek.mondayCopy the code

So if you run it, the output here ismonday. One thing to note hereEnumerated valuesandRawValueAre the twoDifferent thingsFor example, there is no way to assign an enumeration value to oneStringEven if thisenumisStringType.At the same time, there is no way to assign a specific type of data to a specific enumeration type, such as the following exampleSo the aboveprintWhat comes out isSpecific enumeration valuesAnd through theRawValue accessisrawValuetheThe get method.

  • If the enum has no declared type, it has no rawValue attribute

Traversal of an enumeration

So can our enumerations be traversable like collections? The answer is yes

enum week:String {
    case mon, tue, wed, thu, fri = "Hello", sat, sun
}

extension week:CaseIterable{}
var allCase = week.allCases
for c in allCase {
    print(c)
}
Copy the code

Print the following

Associated Value Enumerations

As you can see above, implicit assignment assigns an implicit value to each Case, but sometimes we don’t want to do that, or sometimes we want to use enums to express more complex examples, associating more information. This is where we need to use correlation values. For example, we can use an enumeration value to express a shape such as a circle, a rectangle, or a square. A circle has a radius, a rectangle has a width and a height, and this is where correlation values become very useful

enum Shape {
    case circle(radius: Double)
    case rectangle(width: Int, height: Int)
}
Copy the code

Note that there is no RawValue for ⚠️ after we use the associated value. It’s also easy to understand, because a case can have a set of values for each current case. If you don’t want to write radius, height, and width, it will look like this:

enum Shape {
    case circle(Double)
    case rectangle(Int, Int)
}

Copy the code

You can create an enumeration value with associated values by doing the following

enum Shape { case circle(radius: Double) case rectangle(width: Int, height: Var circle = Shape. Circle (radius: radius)} //****** 10.0) Var Rectangle = shape. rectangle(width: 10, height: 10) //****** 10, height: 10)Copy the code

Other uses of enumerations

Pattern matching

enum Week:String {
    case MONDAY
    case TUEDAY
    case WEDDAY
    case THUDAY
    case FRIDAY
    case SATDAY
    case SUNDAY
}

let currentWeek:Week = .FRIDAY

switch currentWeek{
    case .MONDAY: print(Week.MONDAY.rawValue)
    case .TUEDAY: print(Week.TUEDAY.rawValue)
    case .WEDDAY: print(Week.WEDDAY.rawValue)
    case .THUDAY: print(Week.THUDAY.rawValue)
    case .FRIDAY: print(Week.FRIDAY.rawValue)
    case .SATDAY: print(Week.SATDAY.rawValue)
    case .SUNDAY: print(Week.SUNDAY.rawValue)
}
Copy the code

When using the Switch to match the enum, we must list all the current cases, otherwise the compiler will report an error:If we don’t want to match so many cases, we can use the default keyword to represent the default case

enum Week:String {
    case MONDAY
    case TUEDAY
    case WEDDAY
    case THUDAY
    case FRIDAY
    case SATDAY
    case SUNDAY
}

let currentWeek:Week = .FRIDAY

switch currentWeek{
    case .SATDAY, .SUNDAY: print("Happy Day")
    default : print("Sad Day")

}
Copy the code

If we want to match the associated values

enum Shape { case circle(radius: Double) case rectangle(width: Int, height: Int) } let shape = Shape.circle(radius: 10) switch shape{/* if case matches, we assign 10 to radious*/ case let.circle (radius): print("Circle radius:\(radius)") break case let .rectangle(width, height): print("rectangle width:\(width),height\(height)") break }Copy the code

Or you could write it this way

enum Shape {
    case circle(radius: Double)
    case rectangle(width: Int, height: Int)
}

let shape = Shape.circle(radius: 10.0)

switch shape{
    case .circle(let radius):
        print("Circle radius:\(radius)")
        break
    case .rectangle(let width, var height):
        print("rectangle width:\(width),height\(height)")
        break
    
}
Copy the code

Sometimes in business logic processing we just want to match a single case, we can write like this

Var circle = shape.circle (radius: 10.0) if case let shape.circle (radius) = circle {print(" circle radius:\(radius)")}Copy the code

If we only cared about the same correlation value for different cases, we could write it this way

enum Shape { case circle(radius: Double, diameter: Double) case rectangle(width: Double, height: Double) case square(width: Double, width:Double)} let shape = shape.circle (radius: 10.0, diameter: 20.0) switch shape {case let. circle(x, 20.0), let. square(x, 20.0): print(x) break default: break}Copy the code

Or use a wildcard:

Let shape = shape.circle (radius: 10.0, diameter: 20.0) switch shape {case let. Circle (x, x), let. Square (x, _): print(x) break default: break } /**/ switch shape{ case let .circle(x, y), let .square(y, x): print("x = \(x),y = \(y)") break default: break }Copy the code

Enumeration nested

For example, in our game case, different case combinations will have different skills

Enum CombineDirect{// There are four basic keys enum BaseDirect{case Up case Down case left case Right} // Case of combined keys leftUp(combineElement1: BaseDirect, combineElement2: BaseDirect) case rightUp(combineElement1: BaseDirect, combineElement2: BaseDirect) case leftDown(combineElement1: BaseDirect, combineElement2: BaseDirect) case rightDown(combineElement1: BaseDirect, combineElement2: BaseDirect)} / / use the let leftUp = CombineDirect. LeftUp (combineElement1: CombineDirect. BaseDirect. Left, combineElement2: CombineDirect.BaseDirect.up)Copy the code

Nesting in a structure

struct Skill{

   enum KeyType{
          case up
          case down
          case left
          case right
   }


    let key: KeyType

    func launchSkill(){
        switch key {
        case .left,.right:
            print("left, right")
        case .down,.up:
            print("up, down")
        }
    }
}
Copy the code

Enum Attributes contained in the Enum

The enum can containCalculate attribute.The type attribute, cannot containStorage properties, here is a brief overview:

The Enum contains methods

We can also define instance methods in enUms, static modified methods

enum Week:Int { case MONDAY case TUEDAY case WEDDAY case THUDAY case FRIDAY case SATDAY case SUNDAY mutating func nextDay(){ if self == .SUNDAY { self = Week(rawValue: 1)! }else{ self = Week(rawValue: self.rawValue + 1)! } } } var currentWeek:Week = .FRIDAY print("old current \(currentWeek),rawValue \(currentWeek.rawValue)") currentWeek.nextDay() print("new current \(currentWeek),rawValue \(currentWeek.rawValue)") print("end") <------** Result **----> Old current FRIDAY,rawValue 4 new current SATDAY,rawValue 5 endCopy the code

conclusion

  • 1. The essence of using rawValue in enUms is to call the get method, which is to fetch the string from the corresponding address of Mach-o and return it
  • Init (rawValue 🙂 or enumeration (rawValue 🙂 is triggered
  • 3. The enum has no associated value. If you want to obtain all enumeration values, follow the CaseIterable protocol and obtain them by using the enumeration name. allCase
  • 4. Relationship between case enumeration value and rawValue rawValue: case enumeration value = rawValue rawValue
  • 5. Enumeration with associated value can be three non-enum, because there is no alias RawValue, init, and calculation property RawValue
  • 6. Enum Indicates the mode matching mode. The value can be switch/IF case
  • 7. An enum can be nested or nested in a struct, indicating that the enum is private
  • 8. The enum can contain computing properties and type properties, but cannot contain storage properties
  • 9. You can define an instance + static modifier in an enum