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
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.