What is the difference between `let` and `var` in swift?

后端 未结 30 1307
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 11:09

What is the difference between let and var in Apple\'s Swift language?

In my understanding, it is a compiled language but it does not check

30条回答
  •  攒了一身酷
    2020-11-22 11:37

    It's maybe better to state this difference by the Mutability / Immutability notion that is the correct paradigm of values and instances changeability in Objects space which is larger than the only "constant / variable" usual notions. And furthermore this is closer to Objective C approach.

    2 data types: value type and reference type.

    In the context of Value Types:

    'let' defines a constant value (immutable). 'var' defines a changeable value (mutable).

    let aInt = 1   //< aInt is not changeable
    
    var aInt = 1   //< aInt can be changed
    

    In the context of Reference Types:

    The label of a data is not the value but the reference to a value.

    if aPerson = Person(name:Foo, first:Bar)

    aPerson doesn't contain the Data of this person but the reference to the data of this Person.

    let aPerson = Person(name:Foo, first:Bar)
                   //< data of aPerson are changeable, not the reference
    
    var aPerson = Person(name:Foo, first:Bar)
                   //< both reference and data are changeable.
    

    eg:

    var aPersonA = Person(name:A, first: a)
    var aPersonB = Person(name:B, first: b)
    
    aPersonA = aPersonB
    
    aPersonA now refers to Person(name:B, first: b)
    

    and

    let aPersonA = Person(name:A, first: a)
    let aPersonB = Person(name:B, first: b)
    
    let aPersonA = aPersonB // won't compile
    

    but

    let aPersonA = Person(name:A, first: a)
    
    aPersonA.name = "B" // will compile
    

提交回复
热议问题