Variables

The var keyword define variable.

The let keyword define constant.

Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use Unicode scalar values, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name.

All other Unicode characters are allowed.

Type annotation can be skipped, when variable initialized by value.

// var <variable-name> [: <type-name>] = <value>

let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0

var x = 0.0, y = 0.0, z = 0.0

var welcomeMessage: String
welcomeMessage = "Hello"

let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"

The ? after type name means that variable may have special nil value to indicate a valueless state. It also called optional type.

var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404

serverResponseCode = nil
// serverResponseCode now contains no value

var surveyAnswer: String?
// surveyAnswer is automatically set to nil

if convertedNumber != nil {
    print("convertedNumber contains some integer value.")
}