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

后端 未结 30 1331
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  Happy的楠姐
    2020-11-22 11:39

    Source: https://thenucleargeeks.com/2019/04/10/swift-let-vs-var/

    When you declare a variable with var, it means it can be updated, it is variable, it’s value can be modified.

    When you declare a variable with let, it means it cannot be updated, it is non variable, it’s value cannot be modified.

    var a = 1 
    print (a) // output 1
    a = 2
    print (a) // output 2
    
    let b = 4
    print (b) // output 4
    b = 5 // error "Cannot assign to value: 'b' is a 'let' constant"
    

    Let us understand above example: We have created a new variable “a” with “var keyword” and assigned the value “1”. When I print “a” I get output as 1. Then I assign 2 to “var a” i.e I’m modifying value of variable “a”. I can do it without getting compiler error because I declared it as var.

    In the second scenario I created a new variable “b” with “let keyword” and assigned the value “4”. When I print “b” I got 4 as output. Then I try to assign 5 to “let b” i.e. I’m trying to modify the “let” variable and I get compile time error “Cannot assign to value: ‘b’ is a ‘let’ constant”.

提交回复
热议问题