Skip to content

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 using let by default for safety.
  • var (Variables): Values that can be updated during execution.
swift
let pi = 3.14159   // Constant
var score = 0      // Variable
score = 10         // Reassignment works for var

Stored 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.

swift
var name = "Pirate" // Stored in memory

Computed 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.

swift
// 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, should etc.
  • PascalCase is used for types like Struct, Class or Enum.
swift
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.

TypeWhat It StoresExample
CharacterA single letter, number, or symbol"A"
StringText and words"Pirate"
IntWhole numbers (positive or negative)42
Float32-bit floating-point numbers3.14
Double64-bit floating-point numbers3.14159
BoolBoolean 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.

swift
var name: String = "John" // Explicit declaration
var name = "John" // Inferred as String

Type Conversion

Explicit conversion is required when moving between types.

swift
let stringValue = "42"
let intValue: Int = Int(stringValue) ?? 0 // Using nil-coalescing as fallback

WARNING

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.

swift
let result = 5 / 2          // result is 2
let precise = 5.0 / 2       // precise is 2.5
let casted = Double(5) / 2  // casted is 2.5

Combining Strings and Literals

There are several ways to combine variables with string literals in Swift.

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 String as 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.