Swift enum and switch

Source: Internet
Author: User
Tags case statement


Enumeration:



In fact, everyone is familiar with, a variety of languages have, may be the use of different frequencies.



Brief introduction:



Enumerations define a common data type for a series of associated values, while allowing you to use these values in a type-safe situation while you are programming.



For example: week, month, etc.



The switch is much more than that, but Swift's switch is too powerful for you to be surprised. Hehe ...



The most powerful switch ever struck.



Please see code+ Note:





//
// ViewController.swift
// enum with switch
//
// Created by NapoleonBai on 14-11-17.
// Copyright (c) 2014 NapoleonBai. All rights reserved.
//

import UIKit

/ **
Define enum <definition of enum: keyword: enum>
* /
enum DAYOFWEEK {
    // From Monday to Sunday
    case MONDAY
    case TUESDAY
    case WEDNESDAY
    case THURSDAY
    case FRIDAY
    case SATURDAY
    case SUNDAY
    // Use the keyword case to mark the definition of a new enum member variable (or member)
    / *
    Note: Unlike C or Objective-C, members of enumerated types in Swift are not initially assigned integer values by default. Here, MONDEY, ... SUNDAY is not implicitly equal to 0 by default , 1,2 ... 6. Instead, it is possible to control what type the different enum members will use and what value to assign, which can be specified when defining the DAYOFWEEK enum.
    * /
    
    // Of course, maybe you will ask, then can you just write a case? The answer is allowed
    // eg:
    / *
    case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    // This way of writing is the same as the above, this way saves the case, just use, the number to separate
    * /
    
    // As for initializing the specified value, then this is the case
    // eg:
    / *
    enum DAYOFWEEK: Int {case MONDAY = 0 ...}
    Note: Only when the type is integer, it will grow automatically, other types will not
    * /
}

// Other types of enumeration
enum OtherEnum {
    // defined using tuples
    case ERRORCODE (Int, String)
    case ERRORTYPE (String)
}


class ViewController: UIViewController {

    override func viewDidLoad () {
        super.viewDidLoad ()
        // Do any additional setup after loading the view, typically from a nib.
        // Call: incoming Sunday
        self.managerEnum (DAYOFWEEK.SUNDAY)
        
        // Incoming Wednesday
        self.managerEnum (DAYOFWEEK.WEDNESDAY)
        
        // The above call output:
        // Today: Sunday
        //Today is Wednesday
        
        
        self.managerEnumOther (OtherEnum.ERRORCODE (404, "NOT FOUND"))
        // error code = 404, message = NOT FOUND
        
        self.managerEnumOther (OtherEnum.ERRORTYPE ("Path not found"))
        // errortype = path not found
    }


    
    // This function is used to manage the enumeration
    func managerEnum (mdayOfWeek: DAYOFWEEK) {
        // The above defines an enumeration, which is defined as seven variables from Monday to weekend, here we will use to try the effect
        / *
        Explanation:
        If switch is used to select the output of the enumeration, then all member variables in the enumeration need to be taken into account, otherwise the compilation fails
        Because mdayOfWeek is of DAYOFWEEK type, you can directly use .SUNDAY for output
        * /
        // eg:
        
        // Used to determine the day of the week
        var todayOfWeek = "Sunday";
        
        switch mdayOfWeek {
        case .SUNDAY:
            todayOfWeek = "Sunday"
        case .MONDAY:
            todayOfWeek = "Monday"
        case .TUESDAY:
            todayOfWeek = "Tuesday"
        case .WEDNESDAY:
            todayOfWeek = "Wednesday"
            break
        case .THURSDAY:
            todayOfWeek = "Thursday"
            break
        case .FRIDAY:
            todayOfWeek = "Friday"
            break
        case DAYOFWEEK.SATURDAY:
            todayOfWeek = "Saturday"
            break
        default:
            
            break
        }
        
        println ("Today: \ (todayOfWeek)")
        / *
        What to say here:
        Switch, Switch has been enhanced in Swift.You can see that in the above case statement, there is no increase in break.
        Is it habitual to think back: Will this finish executing one and continue to execute the next one? Until it breaks, then jump out.
        
        The answer is: in swift, the compiler automatically adds a break statement to the case. Each time a case is completed, it automatically breaks.
        So, what if there is a need to perform two or more?
        Then we look at the following:
        * /
        
        // eg:
        
        managerSwitch (2)
        // output:
        / *
        This is 2
        This is 3
        This is 4
        * /
        
        managerSwitch (4) // This is 4
        
        // In this way, it is easy to see that if you want to continue to execute the next case statement, then you need the help of fallthrough, you must remember
        // hee hee
        
        // Well, if there is a demand like this:
        // The company goes to work from Monday to Wednesday, business trips on Thursday and Friday, and rest on Saturday and Sunday
        // Do you think of the above method? In fact, swif provides a more straightforward way, please see
        // eg:
        
        managerSwitchTwo (DAYOFWEEK.FRIDAY)
        
        managerSwitchTwo (DAYOFWEEK.THURSDAY)
        
        managerSwitchTwo (DAYOFWEEK.TUESDAY)
        / *
        Printing in order:
        A business trip ...
        A business trip ...
        Company to work
        * /
        
        //note:
        / *
        There are two things to note:
        Of course, Switch also supports explicit break, usually only in one case, that is, when you do not want to do anything in the default, you can explicitly add a break in the default at this time.
        Fallthrough is not effective in any case. When you use Value Binding technology in Switch, fallthrough is disabled.
        As for what is Value Binding, wait a while. Wait a moment ...
        * /
        
        / *
        The most powerful switch in history: Switch in Swift
        Java Switch does not support strings, but you can also use enumeration instead, even less supported in OC
        But: Swift is different.It supports string, floating point, boolean, and many other data types, and even supports tuple types.
        So, look below
        * /
        
        // eg:
        
        // Interval value:
        var numOne = 50

        switch numOne {
        case 0 ... 100:
            println ("0 ~ 100") // Output: 0 ~ 100
        case 101 ... 200:
            println ("101 ~ 200")
        default:
            "default"
        }
        // About the interval, use "..." to act. In the above case, it is easy to see that the number between 1-100 is intercepted in case 0 ... 100
    
        // About tuples:
        let request = ("status", "success")
        switch request {
        case ("status", "success"):
            println ("success") // Output: success
        case ("status", "failed"):
            println ("failed")
        default:
            "default"
        }
        // Of course, there are many forms of tuples, and you can add values of many data types.If you don't understand, you can move to the tuple column carefully
        //E.g. Skip values that don't care
        // eg:
        let (name, _, age) = ("NapoleonBai", true, 22)
        
        // Here, I almost forgot the value binding mentioned above, so let's borrow a tuple to explain it
        // Of course, for tuples, Switch also supports Value Binding similar to Optional Binding, which can extract the individual values in the tuple and then use it directly below
        
        let requestCode = (404, "NOT FOUND")
        switch requestCode {
        case (404, let state):
println (state) // Output: NOT FOUND
            // fallthrough // error: 'fallthrough' cannot transfer control to a case label that declares vaiables
        case (let errorCode, _):
            println ("error code is \ (errorCode)")
        }
        
        // In this way, it is the use of a VAlue Binding technology, so you cannot use fallthrough. If it is used, the compiler directly throws the above error: it fails to compile. case, then you need to think about it yourself ...
        
        
    }
    
    // explain switch
    func managerSwitch (num: Int) {
        switch num {
        case 1:
            println ("This is 1")
            fallthrough
        case 2:
            println ("This is 2")
            fallthrough
        case 3:
            println ("This is 3")
            fallthrough
        case 4:
            println ("This is 4")
        case 5:
            println ("This is 5")
        default:
            println ("Other")
        }
    }
    
    // swith other operations
    func managerSwitchTwo (day: DAYOFWEEK) {
        switch day {
        case .MONDAY, .TUESDAY, .WEDNESDAY:
            println ("Company to work")
        case .THURSDAY, .FRIDAY:
            println ("Business trip ...")
        default:
            println ("break")
        }
    }
    
    // Print other enums
    func managerEnumOther (otherEnum: OtherEnum) {
        switch otherEnum {
        case .ERRORCODE (let code, let message):
            println ("error code = \ (code), message = \ (message)")
        case .ERRORTYPE (let typeInfo):
            println ("errortype = \ (typeInfo)")
        }
    }
    
    override func didReceiveMemoryWarning () {
        super.didReceiveMemoryWarning ()
        // Dispose of any resources that can be recreated.
    }


}  

Finally introduced a little bit:





We can use the Toraw () function of the enumeration to get its initial value, of course, to have an initial value.



Since there is a member variable to get its initial value, then there is the initial value to find the name of the member variable:



That's the Fromraw () function, which, if not found according to the initial value, returns nil, and note that what is found here is a type of data that is not mandatory, of course,



Here, for the time being, the non mandatory type is understood as an object type. Explain later ...






A day, a weekend break. Hehe


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.