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

后端 未结 6 868
时光说笑
时光说笑 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:50

    Let


    Swift uses two basic techniques to store values for a programmer to access by using a name: let and var. Use let if you're never going to change the value associated with that name. Use var if you expect for that name to refer to a changing set of values.

    let a = 5  // This is now a constant. "a" can never be changed.
    var b = 2  // This is now a variable. Change "b" when you like.
    

    The value that a constant refers to can never be changed, however the thing that a constant refers to can change if it is an instance of a class.

    let a = 5
    let b = someClass()
    a = 6  // Nope.
    b = someOtherClass()  // Nope.
    b.setCookies( newNumberOfCookies: 5 )  // Ok, sure.
    

    Let and Collections


    When you assign an array to a constant, elements can no longer be added or removed from that array. However, the value of any of that array's elements may still be changed.

    let a = [1, 2, 3]
    a.append(4)  // This is NOT OK. You may not add a new value.
    a[0] = 0     // This is OK. You can change an existing value.
    

    A dictionary assigned to a constant can not be changed in any way.

    let a = [1: "Awesome", 2: "Not Awesome"]
    a[3] = "Bogus"             // This is NOT OK. You may not add new key:value pairs.
    a[1] = "Totally Awesome"   // This is NOT OK. You may not change a value.
    

    That is my understanding of this topic. Please correct me where needed. Excuse me if the question is already answered, I am doing this in part to help myself learn.

提交回复
热议问题