Variables in Swift
Our first program will demonstrate how to declare and use variables in Swift. Here’s the full source code:
In Swift, variables are explicitly declared and used by the compiler to check type-correctness of function calls.
var
declares a variable that can be changed later, while let
declares a constant.
You can declare multiple variables at once.
Swift will infer the type of initialized variables.
Unlike some other languages, Swift doesn’t have a concept of “zero-value” for uninitialized variables. Instead, you can use optional types when you want to represent the absence of a value.
Swift uses let
for constants and var
for variables. This is different from some languages that use special syntax for declaration and initialization.
To run the program, save it as variables.swift
and use the Swift compiler:
Now that we can declare and use variables in Swift, let’s continue to explore more features of the language.