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

后端 未结 30 1049
隐瞒了意图╮
隐瞒了意图╮ 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:45

    The let keyword defines a constant:

    let theAnswer = 42
    

    The theAnswer cannot be changed afterwards. This is why anything weak can't be written using let. They need to change during runtime and you must be using var instead.

    The var defines an ordinary variable.

    What is interesting:

    The value of a constant doesn’t need to be known at compile time, but you must assign the value exactly once.

    Another strange feature:

    You can use almost any character you like for constant and variable names, including Unicode characters:

    let                                                                     
    0 讨论(0)
  • 2020-11-22 11:46

    var value can be change, after initialize. But let value is not be change, when it is intilize once.

    In case of var

      function variable() {
         var number = 5, number = 6;
         console.log(number); // return console value is 6
       }
       variable();
    

    In case of let

       function abc() {
          let number = 5, number = 6;
          console.log(number); // TypeError: redeclaration of let number
       }
       abc();
    
    0 讨论(0)
  • 2020-11-22 11:47

    Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant. In C++ it you can define it as const.

    Var is a mutable variable, meaning that it can be changed. In C++ (2011 version update), it is the same as using auto, though swift allows for more flexibility in the usage. This is the more well-known variable type to beginners.

    0 讨论(0)
  • 2020-11-22 11:48

    var is variable which can been changed as many times you want and whenever

    for example

    var changeit:Int=1
    changeit=2
     //changeit has changed to 2 
    

    let is constant which cannot been changed

    for example

    let changeit:Int=1
    changeit=2
     //Error becuase constant cannot be changed
    
    0 讨论(0)
  • 2020-11-22 11:50

    Even though you have already got many difference between let and var but one main difference is:

    let is compiled fast in comparison to var.
    
    0 讨论(0)
  • 2020-11-22 11:52

    let is used to declare a constant value - you won't change it after giving it an initial value.
    var is used to declare a variable value - you could change its value as you wish.

    0 讨论(0)
提交回复
热议问题