Variables & Data Types
A variable is a named storage location that holds a value. In Swift, you must declare how a value is stored using either let or var.
Constants and Variables
let(Constants): Values that do not change once set. Swift encourages usingletby default for safety.var(Variables): Values that can be updated during execution.
let pi = 3.14159 // Constant
var score = 0 // Variable
score = 10 // Reassignment works for varStored vs. Computed
In Swift, variables and constants can either store a value directly or calculate it on the fly.
Stored Variables
These are the most common. They store a value in memory and keep it until it's changed.
var name = "Pirate" // Stored in memoryComputed Variables
These do not actually store a value. Instead, they provide a block of code (a "getter") that runs every time the variable is accessed.
// Version 1: Explicit return
var greeting: String {
return "Ahoy!"
}
// Version 2: Implicit return (Recommended for single-lines)
var greeting: String {
"Ahoy!"
}NOTE
Swift is Type Safe. Once a variable is declared with a specific type, it cannot hold a value of a different type.
Naming Convention
Swift uses camelCase for variables and constants.
- Cannot start with a number or contain spaces.
- Cannot use mathematical symbols: No
+,-,*or/in names. - Boolean names should typically use prefixes like
is,has,shouldetc. PascalCaseis used for types likeStruct,ClassorEnum.
struct UserProfile {
var firstName: String // camelCase
var age: Int
}Primitive Data Types
Primitive data types (also called basic or fundamental types) are the building blocks of data in Swift. They represent single values rather than complex objects and are built into the language itself.
| Type | What It Stores | Example |
|---|---|---|
Character | A single letter, number, or symbol | "A" |
String | Text and words | "Pirate" |
Int | Whole numbers (positive or negative) | 42 |
Float | 32-bit floating-point numbers | 3.14 |
Double | 64-bit floating-point numbers | 3.14159 |
Bool | Boolean values (true or false) | true |
Type Inference
Swift usually infers the type from the initial value, so you don't have to explicitly declare it.
var name: String = "John" // Explicit declaration
var name = "John" // Inferred as StringType Conversion
Explicit conversion is required when moving between types.
let stringValue = "42"
let intValue: Int = Int(stringValue) ?? 0 // Using nil-coalescing as fallbackWARNING
Integer Division: Dividing two integers results in an integer, omitting any decimal points (e.g., 5 / 2 results in 2). To get a precise result, at least one value must be a Double or Float.
let result = 5 / 2 // result is 2
let precise = 5.0 / 2 // precise is 2.5
let casted = Double(5) / 2 // casted is 2.5Combining Strings and Literals
There are several ways to combine variables with string literals in Swift.
let apples = 5
// 1. Comma-separated (print only)
print("I have", apples, "apples.")
// 2. Concatenation (+)
// Works only if all values are Strings; conversion is required for others.
print("I have " + String(apples) + " apples.")
// 3. String Interpolation (Recommended)
// Much cleaner and handles non-string types automatically.
print("I have \(apples) apples.")Why use String Interpolation?
String interpolation (\(variable)) is the preferred method because:
- Readability: It provides a much cleaner syntax that is easier to read and maintain.
- Type Safety: You don't need to manually cast every non-string variable to a
Stringas you do with concatenation. - Performance: It is highly optimized by the compiler to build the final string in one step, making it more memory-efficient than multiple concatenations.
