zoukankan      html  css  js  c++  java
  • Swift guard 关键字

    参考:https://www.cnblogs.com/edensyd/p/9566979.html

    guard expression else { 
        //语句
        //必须包含一个控制语句:return,break,continue或throw。
    }
    
    这里,expression是一个布尔表达式(返回true或者false)。
    如果对表达式求值false,guard则执行代码块内的语句。
    如果对表达式求值true,guard则从执行中跳过代码块内的语句
    

    为啥有if ... else ... 还要用guard ?

     
    class CloseRange {
    
        let start: Int
    
        let end: Int
    
        init?(startValue: Int , endValue: Int) {
    
            guard startValue < endValue else {
    
                print("结束值(endValue) 应大于 起始值(startValue)")
    
                return nil
    
            }
    
            self.start = startValue
    
            self.end = endValue
    
        }
    
    }
    
    let customRange = CloseRange(startValue: 3, endValue: 5)
    if let customRange = customRange {
        print("第一个对象的起始值是:(customRange.start)")
    }
    
    let customRange2 = CloseRange (startValue: 5, endValue: 3)
    if let customRange = customRange2 {
        print("第二个对象的起始值是:(customRange.start)")
    }else{
        print("第二个对象是空对象");
    }
    
    打印:
    结束值3 应大于 起始值5
    
    第二个对象是空对象
    
    此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
  • 相关阅读:
    第01组 Beta冲刺(2/4)
    第01组 Beta冲刺(1/4)
    第01组 Alpha事后诸葛亮
    第01组 Alpha冲刺(4/4)
    第01组 Alpha冲刺(3/4)
    第01组 Alpha冲刺(2/4)
    第01组 Alpha冲刺(1/4)
    提高回顾与个人总结
    软件工程结对作业博客
    软件工程第一次阅读作业
  • 原文地址:https://www.cnblogs.com/liuw-flexi/p/12869810.html
Copyright © 2011-2022 走看看