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

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

    var is the only way to create a variables in swift. var doesn't mean dynamic variable as in the case of interpreted languages like javascript. For example,

    var name = "Bob"
    

    In this case, the type of variable name is inferred that name is of type String, we can also create variables by explicitly defining type, for example

    var age:Int = 20
    

    Now if you assign a string to age, then the compiler gives the error.

    let is used to declare constants. For example

    let city = "Kathmandu"
    

    Or we can also do,

    let city:String = "Kathmandu"
    

    If you try to change the value of city, it gives error at compile time.

提交回复
热议问题