Constants and Variables

Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello").

Declaration

The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future.

Constants

Use the let keyword to declare constants:

let maximumNumberOfLoginAttempts = 10

Variables

Use the var keyword to declare variables:

var currentLoginAttempt = 0

Type Annotations

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store.

var welcomeMessage: String
welcomeMessage = "Hello"

Note: In practice, you rarely need to write type annotations. If you provide an initial value for a constant or variable at the point that you define it, Swift can almost always infer the type to be used for that constant or variable.