关键字学习

convenience:

用在init方法之前。所有的convenience初始化方法都必须调用同一个类中的 designated 初始化完成设置,另外convenience的初始化方法是不能被子类重写或者是从子类中以super的方式被调用的。

class ClassA {
            let numA: Int
            init(num: Int) {
                numA = num
            }
            convenience init(bigNum: Bool) {
                self.init(num: bigNum ? 10000 : 1)
            }
        }
        class ClassB: ClassA {
            let numB: Int
            
            override init(num: Int) {
                numB = num + 1
                super.init(num: num)
            }
        }

只要在子类中实现重写了父类 convenience方法所需要的 init方法的话,我们在子类中就也可以使用父类的 convenience初始化方法了

guard

判断属性是否存在,如果不存在,可以做一些操作

        func apply() -> Bool {
            
            guard let image = UIImage(named:"some")
                else { return false }
            
            ...
            
        }
        

这里的 guard关键字,判读了 UIImage 是否创建成功,如果没有创建成功,在 else 分支中会将函数直接返回。

where

where
关键字的用处非常广泛,在 switch语句,catch分支语句或者条件语句比如 if, while, guard, for-in或者来限制类型的时候。
for-in

    let arr = [1,2,3,4]
    let dict = [1: "one", 2: "two"]
    
    for num in arry where dict[num] != nil {
    //1, 2
    }

do-catch

    enum ResponseError: ErrorType {
        case HTTP(Int)
    }
    
    func errorProne() throws {
        throw ResponseError.HTTP(404)
    }
    
    do {
    try errorProne()
    }catch ResponseError.HTTP(let code) where code >= 400 && code % 2 == 0 {
    print("Bad Request") //match
    }catch ResponseError.HTTP(let code) where code >= 50 && code < 600 {
    print("Internal Server Error")
    }
}

while

    var mutableArray: [Int]? = []
    while let arr = mutableArray  where arr.count < 5 {
    mutableArray?.append(0) //[0,0,0,0,0]
    }

if

    let string: String? = "checkmate"
    if let str = string where str != "checkmate"{
        print("game over")
    }else {
        print("Lte's play")
    }

guard

    let string: String? = "checkmate"
    guard let str = string where str != "checkmate" else{
        fataError("game over")
    }
    print("Let's play")

switch-case

    var value = (1, 2)
    switch value {
    case let (x, y) where x == 1:
    //
    case let (x, y) where x / 5 = 1:
    //
    default:
    
    }

type constraint

    func genericFunction<S where S: StringLiteralConvertible>(string: S) {
        print(string)
    }
    genericFunction("lambada")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 34,561评论 18 399
  • 转眼间,2017年已经过去了十二分之一多,有些人依旧沉醉新年的欢愉之中,有的人却已经悄悄出发,猛然醒悟的我们,只是...
    弟白阅读 213评论 0 0
  • 不会厌倦一首歌的办法就是学会它
    睡眠是条大河阅读 161评论 0 0
  • 上图都用oppo手机拍摄于山西省晋中市常家庄园内。 最后乱入一张昨天拍的雨后学校之景。
    24张三丰阅读 204评论 0 1
  • 《清晨,天空开满金色的花》 文/刘汉皇 蜜蜂在油菜的花蕊苏醒,看着远方的云朵在大地的尽头站立,努力的变幻像一群争抢...
    刘汉皇阅读 617评论 3 3

友情链接更多精彩内容