zoukankan      html  css  js  c++  java
  • 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从句进行扩展:

  • 相关阅读:
    LeetCode数字之和总结
    排序类总结
    web sockect的练习
    RNA速率scVelo
    创建Numpy数组的不同方式
    numpy的课程学习二
    scrapy的cmdline命令和其文件写入乱码问题
    scrapy选择器
    python数据分析的numpy学习笔记
    Numpy的学习笔记一
  • 原文地址:https://www.cnblogs.com/pengsi/p/8514402.html
Copyright © 2011-2022 走看看