In Swift, variables and constants are fundamental building blocks for storing and manipulating data. They play a crucial role in managing information throughout your program.
Variables are containers that hold values which can be changed during program execution. They are declared using the var
keyword.
var age = 25
age = 26 // Value can be changed
Constants, on the other hand, hold values that cannot be modified once they are assigned. They are declared using the let
keyword.
let pi = 3.14159
// pi = 3.14 // This would result in an error
Swift uses Type Inference to automatically determine the data type of a variable or constant based on its initial value. However, you can also explicitly declare the type:
var name: String = "John"
let height: Double = 1.75
Swift uses camelCase for naming variables and constants. Names should be descriptive and meaningful:
let maximumLoginAttempts = 3
var currentLoginAttempt = 0
You can declare multiple variables or constants of the same type in a single line:
var x = 0.0, y = 0.0, z = 0.0
Swift is a type-safe language. This means you can't assign a value of one type to a variable or constant of another type. For more information, see Swift Type Safety.
In Swift, you can use Optionals to represent the absence of a value. This is particularly useful when working with variables that might not have a value:
var possibleNumber: Int? = nil
possibleNumber = 42
Understanding variables and constants is crucial for effective Swift programming. They form the foundation for more advanced concepts like Swift Data Types and Swift Operators.