Variables in Swift
Our first program will demonstrate how to declare and use variables in Swift. Here’s the full source code:
import Foundation
func main() {
// Declares a variable with an initial value
var a = "initial"
print(a)
// You can declare multiple variables at once
var b = 1, c = 2
print(b, c)
// Swift will infer the type of initialized variables
var d = true
print(d)
// Variables declared without a corresponding
// initialization are not allowed in Swift
// Instead, we can use optional types
var e: Int?
print(e ?? 0)
// Swift uses 'let' for constants and 'var' for variables
let f = "apple"
print(f)
}
main()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:
$ swift variables.swift
initial
1 2
true
0
appleNow that we can declare and use variables in Swift, let’s continue to explore more features of the language.