[Swift] About enumeration types

1.First of all


Swift has a very important notation ** called enums ** that we haven't introduced yet. There are so many situations where enums can be very effective, so if you are new to Swift, please take a look at my article. There is also a shared enumeration type in the enumeration type, but I would like to explain this next time.

2. What is an enumeration type?


The enum in Swift is considerably expanded compared to the enum in C, such as the ability to define its own methods. Here is a simple example.

python


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

You have now defined the enumeration Direction. Up and down are called enumeration cases (case). Case names are usually written in camelcase starting with a lowercase letter.

You can also write the previous example as follows:

python


enum Direction {
    case up, down, right, left
}

The enumeration case declared here can be assigned to a variable or constant. Case names are not global and can be described using enum names and ".". However, if you know which enum to be used, you can omit the enum name. This means that ** case names are never used alone, so it's okay to duplicate case names with other enums **. For example.

python


let d = Direction.up          
var x : Direction = .right    //If the type is decided"."Can be described from
d == x                        //These are different values(false)

3. Method definition


Unlike C, Swift allows you to include methods in the definition of enums to represent the behavior and functionality of the type as a whole. For example, let's say you want to know the direction in which the store opened 90 ° clockwise from each direction in the enumeration type that shows the four directions in the example given earlier. This can be defined with a method like this:

python


enum Direction {
    case up, down, right, left
    func clockwise() -> Direction {
        switch self {
            case .up:    return .right
            case .down:  return .left
            case .right: return .down
            case .left:  return .up
        }
    }
}

For example, this method can be used as follows:

python


let d = Direction.up
d.clockwise() == Direction.down              // false
d.clockwise().clockwise() == Direction.down  // true

In this way, the enumerated case and the procedures that depend on it can be defined as one.

4. Value type enumeration


Swift's enums have, in addition to thesimple enums' described so far, ** "value types" ** in which all cases have some value of the same data type. There is. Avalue type enum allows you to define all enumeration casesto have different values of the same type. The type of the value is called thesubstantial type of that enumeration, and the value assigned to each case is called the substantial value. After the newly defined type name, write ":" and substantial type`. You can write a value in each case, but you can only write an integer, a real number, a Bool value, or a string literal. Therefore, what can be a real type is ** a type that can be initialized with these values **. Check out the following overview.

enum type name: entity type{
case Case name=literal
case Case name=literal
    ... ...

If the substantial type is an integer, the case where no value is specified in the literal is the value of the previous case plus one. If there are no literals in the first case, the value will be 0. You can specify the value freely, but you must make sure that no one has the same value.

If substantial type is a string and no literal is specified, the string of the case name will be the value of real type. If the type other than an integer or a string is a substantial type, you must write a literal for each case so that each has a different value.

You can convert types between enums and their real types. Check the following example. Define the Direction type mentioned in the previous example so that the Int type is the entity type.

python


enum Direction : Int {
    case up = 0, down, right, left
}

Since the entity value of the first up is set to 0, the subsequent down, right, and left will have values of 1, 2, and 3, respectively. Assuming you have created several instances of such an enum, you can use a property called rawValue to retrieve the entity value that each has.

python


let a = Direction.right
let i = a.rawValue                // i = 2(Int)
let k = Direction.down.rawValue   // k = 1(Int)

Conversely, to get an instance of the corresponding enum from the value of the entity type, use the initializer init? (RawValue :). This initializer is a failed initializer because the correct value cannot be returned if there is no enumeration case corresponding to the value of the real type. See the example below.

python


let b : Direction? = Direction(rawValue:3)
b! == Direction.left                  // true
if let c = Direction(rawValue:2) {    //Optional binding syntax
    print("OK \(c.rawValue)")         // "OK 2"
}

Let's rewrite the outline we wrote earlier using the value type enumeration. If you define the directional cases in clockwise order, you don't have to enumerate everything in a switch statement. You need to represent the instance itself in the function, but for this we use the reserved word self. Check out the example.

python


enum Direction : Int {
    case up = 0, right, down, left       //Rearrange clockwise
    func clockwise() -> Direction {
        let t = (self.rawValue + 1) % 4  //self is the instance itself
        return Direction(rawValue:t)!    //Will not be nil

5. Methods and properties for enums


You can also define properties for enums, but unlike structs, you can only define ** calculated properties **. Let me give you one example.

python


enum Direction : Int {
    case up = 0, right, down, left  //clockwise
    /* ...Omission... */
    var horizontal: Bool {          //Property definition only for get clause
        switch self {
        case .right, .left: return true
        default: return false
        }
    }
    mutating func turnBack() {
        self = Direction(rawValue:((self.rawValue + 2) % 4))!
    }
}

For the Direction type given as an example so far, we have defined a computational property horizontal that returns true if the value represents horizontal, right or left. This example also shows an example of defining a method with a muting attribute for a enum.

Unlike structs, you change the value of the enum itself stored in a variable by assigning another value to the self that represents itself. Not available if the value is stored in a constant. Here, a method turnBack that inverts in the opposite direction is added to the Direction type.

Let's see an execution example.

python


var d = Direction.left
print(d.rawValue)    //3 is output
d.turnBack()
print(d.rawValue)    //1 is output(Opposite direction of 3)
print(d.horizontal)  //true is output

6. Enum initializers and type methods


You can define type methods, type properties, and initializers for enums as well as structures. For type methods and type methods, write the keyword static at the beginning of the function definition or variable definition. The initializer will define what to assign to self. It is also possible to redefine the automatically prepared initializer init? (RawValue :). Check the example below.

python


enum Direction : Int {
    case up = 0, right, down, left
    static var defaultDirection = Direction.up
    init() {
        self = Direction.defaultDirection
    }
    // ...Omission...
}

Here, a variable called defaultDirection is prepared, and when an instance is created using the initializer init (), this value is used as the initial value.

An execution example is shown below.

python


Direction.defaultDirection = .right    //Set rightward as the initial value
let e = Direction()                    //Use initializer
let g = Direction(rawValue:1)          //Value type enumeration initializer
print(e == g)                          // true

7. Conclusion


This time, I explained enumeration type, which is a very important notation in Swift. Next time, I will write an article about shared enums, so please check it out when the article is uploaded next week. Thank you for reading this far.

Recommended Posts

[Swift] About enumeration types
[Swift] Type type ~ Enumeration type ~
[Swift] About generics
[Swift] Shared enumeration type
[Swift] About protocol extension
About [Cocoa] [Swift] AirPlay 2
Review Swift enum types
[Swift] [Beginner]] About range operators
About Java class loader types
[Swift] About asynchronous processing "Operation"
About types of code coverage
[Swift] I thought about compare
[Swift] "for-in statement" about iterative processing
About =
About Java primitive types and reference types
[Swift] A note about function and closure
Rails: A little summary about data types