美文网首页Swift3.0Swift5.0Swift学习笔记
Swift语法 Swift5 【02 - 流程控制】

Swift语法 Swift5 【02 - 流程控制】

作者: Liwx | 来源:发表于2020-05-08 17:18 被阅读0次

    • 作者: Liwx
    • 邮箱: 1032282633@qq.com
    • 源码: 需要源码的同学, 可以在评论区留下您的邮箱

    iOS Swift 语法 底层原理内存管理分析 专题:【iOS Swift5语法】

    00 - 汇编
    01 - 基础语法
    02 - 流程控制
    03 - 函数
    04 - 枚举
    05 - 可选项
    06 - 结构体和类
    07 - 闭包
    08 - 属性
    09 - 方法
    10 - 下标
    11 - 继承
    12 - 初始化器init
    13 - 可选项


    目录

    • 01-if-else
    • 02-while
    • 03-for
    • 04-for-区间运算符用在数组上
    • 05-区间类型
    • 06-带间隔的区间值
    • 07-switch
    • 08-fallthrough
    • 09-switch注意点
    • 10-复合条件
    • 11-区间匹配、元组匹配
    • 12-值绑定
    • 13-where
    • 14-标签语句

    01-if-else

    • if后面的条件可以省略小括号
    • 条件后面的大括号不可以省略
    • 逗号可以用来可选项绑定
    let age = 28
    if age >= 22, age < 30 {
        print("Gat married")
    } else if age >= 18 {
        print("Being a adult")
    } else if age >= 7 {
        print("Go to school")
    } else {
        print("Just a child")
    }
    
    • 条件后面的大括号不可以省略
    // 报错: Expected '{' after 'if' condition
    if age > 100
        print("age > 100")
    
    • if后面的条件只能是Bool类型
    if age {    // error: cannot convert value of type 'Int' to expected condition type 'Bool'
    
    }
    

    02-while

    • Swift3开始,去除了自增(++), 自减(--)运算符
    // while
    var num = 5
    while num > 0 {
        print("num is \(num)")
        num -= 1
    }// 打印了5次
    
    • repeat-while相当于C语言中的do-while
      • repeat-while至少执行1次
    var num2 = -1
    repeat {
        print("num2 is \(num2)")
    } while num2 > 0
    

    03-for

    • 闭区间运算符...
    let names = ["Anna", "Alex", "Brian", "Jack"]
    for i in 0...3 {
        print(names[i])
    }  // Anna Alex Brian Jack
    
    print("----------")
    
    let range = 1...3
    for i in range {
        print(names[i])
    }  // Alex Brian Jack
    
    print("----------")
    
    let a = 1
    var b = 2
    for i in a...b {
        print(names[i])
    }  // Alex Brian
    
    print("----------")
    for i in  a...3 {
        print(names[i])
    }  // Alex Brian Jack
    
    • for 接收参数默认声明为let,可以声明为var
    // i默认是let, 有需要时可以声明为var
    for var i in 1...3 {
        i += 5
        print(i)
    }  // 6 7 8
    
    • 使用下划线_忽略
    // _ 忽略
    for _ in 1...3 {
        print("for")
    }  // for for for
    
    • 半开区间运算符
    // - 半开区间运算符: a..<b , 取值 a <= 取值 < b
    for i in 1..<5 {
        print(i)
    }  // 1 2 3 4
    

    04-for-区间运算符用在数组上

    let names = ["Anna", "Alex", "Brian", "Jack"]
    for name in names[0...3] {
        print(name)
    } // Anna Alex Brian Jack
    
    • 单侧区间: 让区间朝一个方向尽可能的远
    for name in names[2...] {
        print(name)
    } // Brian Jack
    
    for name in names[...2] {
        print(name)
    } // Anna Alex Brian
    
    for name in names[..<2] {
        print(name)
    } // Anna Alex
    
    • 判断是否在区间内
    let range = ...5
    range.contains(7)   // false
    range.contains(4)   // true
    range.contains(-3)  // true
    

    05-区间类型

    • 闭区间类型ClosedRange
    // 闭区间
    let range1: ClosedRange<Int> = 1...3
    
    • 区间类型Range
    let range2: Range<Int> = 1..<3
    
    • 半开区间类型PartialRangeThrough
    let range3: PartialRangeThrough<Int> = ...5
    

    • 字符字符串也能使用区间运算符,但默认不能用在for-in
    let stringRange1 = "cc"..."ff"  // ClosedRange<String>
    stringRange1.contains("cb") // false
    stringRange1.contains("dz") // true
    stringRange1.contains("fg") // false
    
    let stringRange2 = "a"..."f"    // ClosedRange<String>
    stringRange2.contains("d")  // true
    stringRange2.contains("h")  // false
    
    • 字符区间必须指明Character类型, 否则编译器自动推导为String类型
    // \0到~包括了所有可能要用到的ASCII字符
    // 定义字符区间必须指明Character类型,否则编译器自动推导为String类型
    let characterRange: ClosedRange<Character> = "\0"..."~"
    characterRange.contains("G")    // true
    

    06-带间隔的区间值

    • stride定义
    ///   - start: 从start值开始
    ///   - through: 依次累加through
    ///   - stride: 到stride结束,不超过stride
    public func stride<T>(from start: T, through end: T, by stride: T.Stride) -> StrideThrough<T> where T : Strideable
    
    let hours = 11
    let hourInterval = 2
    // tickMark的取值: 从4开始, 累加2, 不超过11
    for tickMark in stride(from: 4, through: hours, by: hourInterval) {
        print(tickMark)
    }   // 4 6 8 10
    

    07-switch

    • case default后面不能写大括号{}

    • default后面至少有一条语句,不能写分号,因为分号不是语句。通常没有其他处理就用break

    var number = 2
    switch number {
    case 1:
        print("number is 1")
        break
    case 2:
        print("number is 2")
        break
    case 3:
        print("number is 3")
        break
    default:
        break   // default后面至少有一条语句,不能写分号,因为分号不是语句
        //    print("number is \(number)")
    }   // number is 2
    

    • case默认可以不写break, 并不会贯穿到后面的条件
    var number1 = 1
    switch number1 {
    case 1:
        print("number1 is 1")
    case 2:
        print("number1 is 2")
    default:
        print("number1 is other")
    } // number1 is 1
    

    08-fallthrough

    • 使用fallthrough可以实现贯穿效果
    var number = 1
    switch number {
    case 1:
        print("number is 1")
        fallthrough
    case 2:
        print("number is 2")
    default:
        break
    }
    // number is 1
    // number is 2
    

    09-switch注意点

    • switch必须要保证能处理所有情况
    // error: switch must be exhaustive
    var number = 1
    switch number {
    case 1:
        print("number is 1")
    case 2:
        print("number is 2")
    }
    
    • case、default后面至少要有一条语句

    如果不想做任何事,加个break即可

    var number = 1
    switch number {
    case 1:
        print("number is 1")
    case 2:
        print("number is 2")
    default:
        break
    }
    
    • 如果能保证已处理所有情况, 也可以不必使用default
    enum Answer {case right, wrong}
    let answer = Answer.right
    switch answer {
    case Answer.right:
        print("right")
    case Answer.wrong:
        print("wrong")
    }
    
    // 由于已确定answer是Answer类型,因此可以省略Answer
    switch answer {
    case .right:
        print("right")
    case .wrong:
        print("wrong")
    }
    

    10-复合条件

    • switch也支持CharacterString类型
    let string = "Jack"
    switch string {
    case "Jack":
        fallthrough    // 贯穿
    case "Rose":
        print("Right person")
    default:
        break
    } // Right person
    
    // 等价于上面
    switch string {
    case "Jack", "Rose":
        print("Right person")
    default:
        break
    } // Right person
    
    let character: Character = "a"
    switch character {
    case "a", "A":
        print("The letter A")
    default:
        print("Not the letter A")
    }  // The letter A
    

    11-区间匹配、元组匹配

    • swift区间条件匹配
    let count = 62
    switch count {
    case 0:
        print("none")
    case 1..<5:
        print("a few")
    case 5..<12:
        print("several")
    case 12..<100:
        print("dozens of")
    case 100..<1000:
        print("hundreds of")
    default:
        print("many")
    } // dozens of
    
    • 可以使用下划线_忽略某个值
    let point = (1, 1)
    switch point {
    case (0, 0):
        print("the origin")
    case (_, 0):
        print("on the x-axis")
    case (0, _):
        print("on the y-axis")
    case (-2...2, -2...2):
        print("inside the box")
    default:
        print("outside of the box")
    } // inside the box
    

    12-值绑定

    值绑定就是将相应的值 绑定到常量/变量。值绑定默认为let, 必要时let也可以改为var

    let point = (2, 0)
    switch point {
    case (let x, 0):
        print("on the x-axis with an x value of \(x)")
    case (0, let y):
        print("on the y-axis with an y value of \(y)")
    case (let x, let y):
        print("somewhere else at (\(x), \(y))")
    }
    // on the x-axis with an x value of 2
    

    13-where

    • where 条件过滤
    • whereswitch中使用
    let point = (1,-1)
    switch point {
    case let (x, y) where x == y:
        print("on the line x == y")
    case let (x, y) where x == -y:
        print("on the line x == -y")
    case let (x, y):
        print("(\(x), \(y)) is just some arbitrary point")
    } // on the line x == -y
    
    • wherefor-in中使用
    // 将所有正数加起来
    var numbers = [10, 20, -10, -20, 30, -30]
    var sum = 0
    for number in numbers where number > 0 {
        sum += number
    }
    print(sum)  // 60
    

    14-标签语句

    • 使用continue, break 进行标签跳转
    outer: for i in 1...4 {
        for k in 1...4 {
            if k == 3 {
                continue outer
            }
            if i == 3 {
                break outer
            }
            print("i == \(i), k == \(k)")
        }
    }
    // i == 1, k == 1
    // i == 1, k == 2
    // i == 2, k == 1
    // i == 2, k == 2
    

    iOS Swift 语法 底层原理内存管理分析 专题:【iOS Swift5语法】

    下一篇: 03 - 函数
    上一篇: 01 - 基础语法


    相关文章

      网友评论

        本文标题:Swift语法 Swift5 【02 - 流程控制】

        本文链接:https://www.haomeiwen.com/subject/bcxqnhtx.html