美文网首页
Swift语法备忘录2-Control Flow

Swift语法备忘录2-Control Flow

作者: 叶子扬 | 来源:发表于2018-01-06 17:04 被阅读0次

    使用if 或者 swith进行条件判断,
    使用for-in,while,和 repeat-while进行循环
    if 后面的()是可选的【例如下边的 if score > 50】,但是其后的{}必须有(非可选)

    let individualScores = [75, 43, 103, 87, 12]
    var teamScore = 0
    for score in individualScores {
        if score > 50 {
            teamScore += 3
        } else {
            teamScore += 1
        }
    }
    print(teamScore)
    

    注意:条件判断中,描述必须是一个明确的bool值,不能含蓄的跟0作比较。也就是必须是yes或者no,不能跟0还是非0做参考

    optionals
    /You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional./
    用国人的话来说就是:如果一个变量可能有值,也可能没有值,就在初始化的时候添加一个问号?。
    另外,声明变量的时候不添加?,编译不通过

    var optionalString: String? = "Hello"
    print(optionalString == nil)
    
    var optionalName: String? = nil"John Appleseed"
    var greeting = "Hello!"
    if let name = optionalName {
        greeting = "Hello, \(name)"
        print(greeting)
    }else{
        print("your name is nil")
    }
    

    ?? 如果第一个为nil,就选择 ?? 后边的值

    let nickName: String? = nil
    let fullName: String = "John Appleseed"
    let informalGreeting = "Hi \(nickName ?? fullName)"
    print(informalGreeting)
    

    Switch
    /Switches support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality./
    支持各种数据类型,以及更多的变量对比(只要符合条件就执行)

    let vegetable = "red pepper"
    switch vegetable {
    case "celery":
        print("Add some raisins and make ants on a log.")
    case "cucumber", "watercress":
        print("That would make a good tea sandwich.")
    case let x where x.hasSuffix("pepper"):
        print("Is it a spicy \(x)?") Is it a spicy red pepper?
    default:
        print("Everything tastes good in soup.")
    }
    

    注意:
    1.注释default报错:Switch must be exhaustive(详尽)
    2.case后边不再有break,只要满足了一个case,程序就不会再去判断其他case并执行

    是否for-in遍历字典的时候,因为字典是无序的集合,因此取出的keys也是任意的顺序的

    let interestingNumbers = [
        "Prime": [2, 3, 5, 7, 11, 13],
        "Fibonacci": [1, 1, 2, 3, 5, 8],
        "Square": [1, 4, 9, 16, 25],
    ]
     标记上面哪组拥有最大的数
    var largest = 0
    var lagestName:String? = nil
    for (kind, numbers) in interestingNumbers {
        for number in numbers {
            if number > largest {
                largest = number
                lagestName = kind
            }
        }
    }
    print(lagestName)
    print(largest)
    

    /* 注意:print(lagestName)会有警告,fix的方案有三:
    1.print(lagestName ?? <#default value#>)
    2.print(lagestName!)
    3.print(lagestName as Any)
    */

    Use while to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.

    var n = 2
    while n < 100 {
        n *= 2
    }
    print(n) 128
    
    var m = 2
    repeat {
        m *= 2
    } while m < 100
    print(m) 128
    

    使用 ..< 表示某个索引的范围

    var total = 0
    for i in 0..<4 {
        total += i
    }
    print(total)  6
    
     使用 ... 表示某个索引的范围【包含最后一个范围,即:(0..<=4)这个表达式写法是错的,这里就是表达这个意思而已】
    var total2 = 0
    for i in 0...4 {
        total2 += i
    }
    print(total2)  10
    

    相关文章

      网友评论

          本文标题:Swift语法备忘录2-Control Flow

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