If you’re just getting started with Swift, you’ll quickly realise that everything revolves around data—numbers, text, true/false values, lists of things. Understanding Swift’s basic data types is like learning the alphabet before you write sentences. This post covers the essential building blocks you’ll use in every Swift project.

What are Data Types?

A data type defines the kind of data you’re working with and what actions you can perform on it. Are you handling a number or a name? A true/false flag or a list of groceries? Swift is a strongly typed language, which means you must be clear about what types you’re working with. Swifts compiler will catch errors early if you make mistakes.

Let’s explore Swift’s basic building blocks for handling data.


Integers: When You Need Whole Numbers

Think of integers as your go-to for counting anything that doesn’t involve fractions—like the number of users who signed up today or the high score in your game.

Example:

let numberOfApples: Int = 5
let temperature: Int = -3

Swift provides several integer types, such as Int (adapts to your platform), Int64, UInt8, etc. For most purposes, Int is fine.

Typical Use Cases:

  • Counting things like users, inventory items, or steps taken
  • Working with array indices and loop counters
  • Storing whole number values like ages, scores, or years

Floating Point Numbers: Decimals

When you need decimal numbers (not just whole numbers), use Double or Float.

Example:

let price: Double = 19.99
let pi: Float = 3.14159
  • Double is what you’ll use 99% of the time. It’s precise and handles large numbers well.
  • Float saves memory but sacrifices precision. I rarely use it.

Typical Use Cases:

  • Calculating precise measurements and scientific formulas
  • Handling money and prices in financial applications
  • Working with coordinates, percentages, and real-world measurements

Note: For money in real-world apps, consider using Decimal for better accuracy.


Strings: Text and Characters

A String represents a chain of text—words, sentences, or any collection of characters.

Example:

let greeting: String = "Hello, world!"
let username = "programmer42"
let emoji = "✨"

You can combine strings:

let fullMessage = greeting + " Welcome, " + username + "!"

Fun Fact: Swift treats emojis or even complex Unicode as valid strings.

Typical Use Cases:

  • User input and form data
  • Displaying messages and labels in your app’s interface
  • API responses and configuration settings

Booleans: True or False

Bool is the type for logical values: just true or false. This is the core of conditionals, logic, and flow control.

Example:

let isUserLoggedIn: Bool = true
let hasFinishedLevel = false

You’ll use booleans most with if statements:

if isUserLoggedIn {
    print("Show dashboard")
} else {
    print("Ask user to log in")
}

Typical Use Cases:

  • Form validation and user interface states
  • Feature toggles and configuration flags
  • Game state management (paused, playing, game over)

Arrays: Ordered Lists

An Array stores a list of values, all of the same type, in an ordered sequence.

Example:

let highScores: [Int] = [85, 99, 72]
let shoppingList = ["milk", "eggs", "cheese"]

You can access items by their index (starting from 0):

let firstItem = shoppingList[0] // "milk"

Arrays are flexible: add, remove, and sort items as needed.

Typical Use Cases:

  • Storing collections of similar items (shopping lists, high scores)
  • Managing user interface elements (table view data sources)
  • Processing sequences of data (batch operations)

Dictionaries: Key-Value Pairs

A Dictionary (sometimes called a “Map” in other languages) connects keys to values.

Example:

var studentGrades: [String: Int] = [
    "Anya": 91,
    "Ben": 85,
    "Charlotte": 98
]

Access a value by its key:

let anyaGrade = studentGrades["Anya"] // Optional(91)

Typical Use Cases:

  • Storing configuration settings and preferences
  • Mapping unique identifiers to data (user IDs to profiles)
  • Caching and lookup tables

Optionals: Data That Might Be Missing

Sometimes, a value might be missing (nil). Swift uses optionals to make this explicit, so you don’t accidentally process non-existent data.

Example:

var middleName: String? = nil // "?" means "may be String, or nil"
middleName = "Grace"

You must “unwrap” optionals to use them safely:

if let name = middleName {
    print("Middle name is \(name)")
} else {
    print("No middle name provided.")
}

Typical Use Cases:

  • Handling potentially missing user input
  • API responses that may not contain all fields
  • Database queries that might return no results

Type Inference

Swift often figures out types for you:

let points = 100          // Int
let isActive = false      // Bool
let pi = 3.14             // Double
let tags = ["swift", "ios", "beginner"] // [String]

But you should be explicit when it helps readability or understanding. For example, here are three situations where explicit types might be better:

1. When the default type isn’t what you want:

let price: Float = 19.99        // Without this, Swift assumes Double
let userID: Int64 = 12345       // For large numbers or API compatibility

2. When working with empty collections:

let scores: [Int] = []          // Clear what type of array this will hold
let settings: [String: Any] = [:]  // Dictionary type is obvious

3. When the intent isn’t obvious from context:

let timeout: TimeInterval = 30  // More descriptive than just Double
let completion: (() -> Void)? = nil  // Makes the closure type clear

Wrapping Up

These are Swift’s fundamental data types: Int, Double, String, Bool, Array, Dictionary, and Optional. Mastering these basics will take you far—most Swift code you read or write is built from these! As your projects grow, you’ll discover how they can be combined and extended.

Happy coding!