How exactly does the “let” keyword work in Swift?

后端 未结 6 859
时光说笑
时光说笑 2020-12-02 23:27

I\'ve read this simple explanation in the guide:

The value of a constant doesn’t need to be known at compile time, but you must assign it a value exa

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 23:42

    It's best to think of let in terms of Static Single Assignment (SSA) -- every SSA variable is assigned to exactly once. In functional languages like lisp you don't (normally) use an assignment operator -- names are bound to a value exactly once. For example, the names y and z below are bound to a value exactly once (per invocation):

    func pow(x: Float, n : Int) -> Float {
      if n == 0 {return 1}
      if n == 1 {return x}
      let y = pow(x, n/2)
      let z = y*y
      if n & 1 == 0 {
        return z
      }
      return z*x
    }
    

    This lends itself to more correct code since it enforces invariance and is side-effect free.

    Here is how an imperative-style programmer might compute the first 6 powers of 5:

    var powersOfFive = Int[]()
    for n in [1, 2, 3, 4, 5, 6] {
        var n2 = n*n
        powersOfFive += n2*n2*n
    }
    

    Obviously n2 is is a loop invariant so we could use let instead:

    var powersOfFive = Int[]()
    for n in [1, 2, 3, 4, 5, 6] {
        let n2 = n*n
        powersOfFive += n2*n2*n
    }
    

    But a truly functional programmer would avoid all the side-effects and mutations:

    let powersOfFive = [1, 2, 3, 4, 5, 6].map(
        {(num: Int) -> Int in
            let num2 = num*num
            return num2*num2*num})
    

提交回复
热议问题