枚举、嵌套枚举以及枚举的属性和方法

67 阅读1分钟

今天学习了枚举

其中,嵌套枚举和在枚举中使用方法印象深刻。

嵌套枚举中,内层的枚举和在枚举中使用的方法属于一个层级,如果在外层枚举中使用了一个方法(函数)并联合使用了switch  self语句,那么switch匹配的智能是外层的枚举。因为此方法是一个实例方法,需要配合枚举的值进行switch匹配。一下是一个例子。

enum 会员等级 {
    case 免费会员, 银卡会员, 金卡会员
    
    enum 权限 {
        case 观看旧片, 跳过广告, 下载影片, 观看新片
    }
    
    var 费用: Int {
        switch self {
        case .免费会员:
            return 0
        case .银卡会员:
            return 250
        case .金卡会员:
            return 400
        }
    }
    
    func 可以使用(_ 权限: 会员等级.权限) -> Bool {
        switch self {
              
        case .免费会员:
            return 权限 == .观看旧片
        case .银卡会员:
            return 权限 != .观看新片
        case .金卡会员:
            return true
        }
    }
}