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

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

    let defines a "constant". Its value is set once and only once, though not necessarily when you declare it. For example, you use let to define a property in a class that must be set during initialization:

    class Person {
    
        let firstName: String
        let lastName: String
    
        init(first: String, last: String) {
             firstName = first
             lastName = last
             super.init()
        }
    }
    

    With this setup, it's invalid to assign to firstName or lastName after calling (e.g.) Person(first:"Malcolm", last:"Reynolds") to create a Person instance.

    You must define a type for all variables (let or var) at compile time, and any code that attempts to set a variable may only use that type (or a subtype). You can assign a value at run time, but its type must be known at compile time.

提交回复
热议问题