Swift4.0复习扩展

1.扩展计算式属性:

2.对方法进行扩展:

/// 定义枚举类型Light,
/// 它指定了基本类型String
enum Light: String {
    case red = "red"
    case green = "green"
    case blue = "blue"
}
 
/// 对Light枚举类型进行扩展
extension Light {
     
    /// 扩展出不带参数的初始化器方法
    init() {
        // 这里默认值设定为red
        self = .red
    }
     
    /// 扩展出描述方法
    func discribe() -> String {
        return self.rawValue
    }
     
    /// 扩展出下标
    subscript(index: Int) -> Light {
        let matchStrings = ["red", "green", "blue"]
        // 找到当前枚举值所处的索引位置
        let currIndex = matchStrings.index {
            return $0 == self.rawValue
        }!
        // 将当前索引位置与指定的索引相加,
        // 然后模2,
        // 得到最终的枚举值
        return Light(rawValue: matchStrings[(currIndex + index) % 3])!
    }
}
 
// 使用扩展出的初始化器方法创建Light枚举实例
let light = Light()
 
// 调用扩展出的discribe方法
print("current light: \(light.discribe())")
 
// 使用扩展出的下标
print("light[0] = \(light[0])")
print("light[1] = \(light[1])")
print("light[2] = \(light[2])")
 

3.对协议的扩展:

4.对已有类型做协议遵循的扩展:

5.对泛型类型进行扩展:

6.用一条泛型where从句进行扩展:

 

posted on 2018-03-06 15:03  玉思盈蝶  阅读(136)  评论(0编辑  收藏  举报

导航