zoukankan      html  css  js  c++  java
  • Swift-枚举enum理解

    //定义一个枚举
    //枚举的语法,enum开头,每一行成员的定义使用case关键字开头,一行可以定义多个关键字
    enum CompassPoint {
        case North
        case South
        case East
        case West
    }
    //多成员也可以出现在一行上,用逗号分开
    //原始值可以是字符串,字符,或任何整数或浮点数类型。每个原始值必须在它的枚举中唯一声明。当整数被用于原始值,如果其他​​枚举成员没有值时,它们自动递增。
    enum CompassPoint1:Int {
        case North = 1,South,East,Weet
    }
    var dir = CompassPoint1(rawValue: 1)
    var dirNum = CompassPoint1.South.rawValue
    
    
    //使用枚举
    var direction = CompassPoint.East
    //再次修改时可以不指定枚举,而可以只使用.引用
    direction = .North
    //注意:不像C和Objective-C,Swift枚举成员在创建时不分配默认整数值。在上面的例子CompassPoints中North,South,Eath,West不等于隐含0,1,2和3,而是一种与CompassPoint明确被定义的类型却各不相同的值。
    func test(dir:CompassPoint) -> CompassPoint {
        return dir
    }
    
    test(CompassPoint.East)
    
    //可以使用单个枚举值匹配switch语句
    
    var myDirection = CompassPoint.East
    myDirection = .East
    
    
    switch myDirection {
    case .North:
        print("Lots of planets have a north")
    case .South:
        print("Watch out for penguins")
    case .East:
        print("Where the sun rises")
    case .West:
        print("Where the skies are blue")
    }
    //以上代码可以这样理解:你可以理解这段代码:“考虑directionToHead的价值。当它等于North,打印“Lots of planets have a north”。当它等于South,打印“Watch out for penguins”等等。正如控制流所描述,Switch语句考虑枚举的成员,如果省略了West时,这段代码无法编译,因为它没有考虑CompassPoint成员的完整性。Switch语句要求全面性确保枚举成员,避免不小心漏掉情况发生。当它不需要为每一个枚举成员都匹配的情况下,你可以提供一个默认default分支来涵盖未明确提到的任何成员:
    
    switch myDirection{
    case .West:
        print("East")
    default:
        print("other")
    }
  • 相关阅读:
    ADB命令大全
    Backup your Android without root or custom recovery -- adb backup
    Content portal for Pocketables Tasker articles
    Is there a way to detect if call is in progress? Phone Event
    Tasker to proximity screen off
    Tasker to detect application running in background
    Tasker to create toggle widget for ES ftp service -- Send Intent
    Tasker to proximity screen on
    Tasker to answer incoming call by pressing power button
    Tasker to stop Poweramp control for the headset while there is an incoming SMS
  • 原文地址:https://www.cnblogs.com/WJJ-Dream/p/5806916.html
Copyright © 2011-2022 走看看