SWIFT
Swift Variables: Syntax, Usage, and Examples
Variables in Swift store and manage data in a program. They hold values that can change during execution, making them essential for dynamic applications. Swift provides different ways to declare variables, each with specific use cases.
How to Declare Variables in Swift
Use the var
keyword to declare a variable in Swift. The variable’s type is inferred based on the assigned value, but you can also specify it explicitly.
var name = "Alice" // String inferred
var age: Int = 30 // Explicit type annotation
var isLoggedIn = false // Boolean inferred
Once a variable is declared, update its value freely.
name = "Bob" // Allowed, because name is declared as a variable
age = 35 // Allowed
Use let
instead of var
when the value should not change. Constants prevent accidental modifications.
let birthYear = 1993
// birthYear = 2000 // Error: Cannot assign to a constant
When to Use Variables in Swift
Variables allow you to manage state, store data, and create dynamic behaviors. Use variables in Swift for:
1. Storing User Input
When building interactive applications, variables store user responses.
var username = ""
username = "Charlie"
print("Welcome, \(username)!")
2. Tracking Application State
Use variables to track whether a user is logged in, a feature is enabled, or a session is active.
var isDarkModeEnabled = false
isDarkModeEnabled = true
3. Performing Calculations
Mathematical operations require variables to store and update values dynamically.
var score = 0
score += 10 // Increases score by 10
print("Current score: \(score)")
Examples of Variables in Swift
Variables are widely used in Swift applications. Here are some examples:
Declaring Variables
Declare and modify variables in Swift.
var city = "Paris"
city = "New York"
print(city) // Output: New York
Using Variables in Functions
Pass and modify variables inside functions.
func greetUser(name: String) {
print("Hello, \(name)!")
}
var user = "Alice"
greetUser(name: user)
Variables in Loops
Variables store counters or accumulators inside loops.
var total = 0
for i in 1...5 {
total += i
}
print(total) // Output: 15
Variables with Optionals
Optional variables can hold a value or nil
.
var optionalName: String? = "Alice"
print(optionalName ?? "Guest") // Output: Alice
optionalName = nil
print(optionalName ?? "Guest") // Output: Guest
Learn More About Variables in Swift
Swift provides additional functionality for working with variables, including computed properties, global variables, and environment variables.
Variable vs. Constant
Use var
for values that change and let
for values that remain constant.
var score = 10
score += 5 // Allowed
let maxScore = 100
// maxScore = 200 // Error: Cannot assign to a constant
Static Variables in Swift
Use static var
to define properties shared across all instances of a class or struct.
struct Settings {
static var theme = "Light"
}
print(Settings.theme) // Output: Light
Computed Variables in Swift
Computed properties calculate values dynamically instead of storing them.
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
let rect = Rectangle(width: 5, height: 10)
print(rect.area) // Output: 50
Global Variables
Define global variables outside of functions or types for use throughout the program.
var appLanguage = "English"
func printLanguage() {
print("Current language: \(appLanguage)")
}
printLanguage() // Output: Current language: English
Override Variables in Subclasses
Use override var
to modify inherited properties.
class Animal {
var sound: String {
return "Unknown"
}
}
class Dog: Animal {
override var sound: String {
return "Bark"
}
}
let myDog = Dog()
print(myDog.sound) // Output: Bark
Swift Environment Variables
Retrieve environment variables using ProcessInfo
.
if let path = ProcessInfo.processInfo.environment["PATH"] {
print("System Path: \(path)")
}
Checking the Type of a Variable
Use type(of:)
to determine a variable's type at runtime.
let num = 42
print(type(of: num)) // Output: Int
Printing Variables in Swift
Use print()
to display variable values.
var message = "Hello, Swift!"
print(message) // Output: Hello, Swift!
Public and Private Variables
Swift allows different access levels for variables.
class User {
public var name = "Alice" // Accessible from anywhere
private var password = "1234" // Accessible only inside the class
}
let user = User()
print(user.name) // Allowed
// print(user.password) // Error: password is private
Best Practices for Using Variables in Swift
- Use
let
when possible – If a value should not change, declare it as a constant. - Choose meaningful names – Avoid generic names like
x
ortemp
. - Group related variables – Organize variables in structures or classes.
- Avoid magic numbers – Define constants instead of using hardcoded values.
- Minimize the use of global variables – Keep variables within the smallest possible scope to reduce unintended side effects.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.