Get 50% off during WWDC 2025!

Design+Code logo

Quick links

Suggested search

1. Foundation of Swift: Variables and Constants

Every app we build needs to store and manage data - from user preferences to game scores, from temporary calculations to fixed configuration values. In Swift, we handle this data using two fundamental tools: variables and constants. Think of these as containers that hold different types of information in your app. Screenshot 2025-02-19 at 9.26.19 PM

A. What is Mutability?

In Swift, mutability refers to whether something can be changed after it's created. Think of it like writing with a pencil versus a permanent marker. Variables are mutable (can be changed), while constants are immutable (cannot be changed). This distinction helps us write safer, more predictable code.

B. Declaring Variables and Constants

Let's explore how to create and use variables and constants in Swift. The syntax is straightforward, but the choice between them can significantly impact your code's safety and intent:

// Variables - Use 'var' when values need to change
@State var playerScore = 0          // Starting score
playerScore = 100           // Player earned points!
playerScore += 50           // Bonus points added

// Constants - Use 'let' when values should remain fixed
let maxScore = 1000         // Maximum possible score
let gameTitle = "Space Adventure"
maxScore = 2000            // đźš« Error: Cannot change a constant

2. Type Safety in Swift

One of Swift's most powerful features is its strong type system. Unlike some programming languages where values can be freely converted between different types, Swift ensures type safety at compile time. This means you'll catch type-related errors before your app even runs, making your code more reliable and easier to debug.

A. Understanding Types

Think of types as categories that tell Swift exactly what kind of data you're working with. Just like you wouldn't put a book in your refrigerator, Swift ensures that data is used appropriately according to its type.

Swift provides several built-in types to handle different kinds of data:

// String - for text data
var playerName: String = "Alex"
var welcomeMessage = "Welcome to the game!"  // Type inferred as String

// Integer - for whole numbers
var score: Int = 42
var levelNumber = 1         // Type inferred as Int

// Double - for decimal numbers (high precision)
var playerHealth: Double = 100.0
var damageMultiplier = 1.5  // Type inferred as Double

// Boolean - for true/false values
var isGameOver: Bool = false
var isPaused = true         // Type inferred as Bool

Each type has specific properties and operations that make sense for that kind of data. For example:

  • You can add numbers together (score + 10)
  • You can combine strings (playerName + " wins!")
  • You can toggle boolean values (isGameOver = !isGameOver)

B. Understanding Number Types

Swift provides different numeric types to handle various scenarios in your apps. Choosing the right type is crucial for both accuracy and performance.

Working with Decimal Numbers

i. Double - The Go-To Choice

// Double provides high precision (15-17 decimal digits)
var bankBalance: Double = 1234.56
var scientificMeasurement = 3.141592653589793
var itemPrice = 19.99  // Swift automatically makes this a Double

Key features of Double:

  • High precision for accurate calculations
  • Default choice for decimal numbers in Swift
  • Perfect for:

    • Financial calculations (prices, currencies)
    • Scientific computations
    • Any calculation where precision matters
    • User-facing decimal values
// Examples of Double in action
let taxRate = 0.08
let itemPrice = 29.99
let taxAmount = itemPrice * taxRate  // Precise calculation

ii. Float - When Memory Matters

// Float provides standard precision (6-7 decimal digits)
var temperature: Float = 72.8
var distance: Float = 1000.5

Key features of Float:

  • Uses less memory than Double
  • Suitable for:

    • Graphics and 3D coordinates
    • Simple measurements
    • Situations where extreme precision isn't critical
    • Performance-critical code with many decimal numbers
// Examples of Float usage
let graphicsXCoordinate: Float = 123.45
let graphicsYCoordinate: Float = 67.89

iii. Making the Right Choice

// When to use Double
struct ProductPrice {
    let amount: Double  // Good! Precise for money
    let tax: Double    // Good! Financial calculations
}

// When to use Float
struct GraphicsPoint {
    let x: Float  // Good! Memory-efficient for graphics
    let y: Float  // Good! Standard precision is enough
}

C. Best Practices

i. Default to Double

// Let Swift infer the type
let price = 19.99      // Automatically a Double
let score = 100.0      // Automatically a Double

ii. Be Explicit When Needed

// Explicitly declare Float when needed
let position: Float = 1234.5  // For graphics

iii. Avoid Mixing Types

let double1: Double = 3.14
let float1: Float = 2.71

// This would cause an error:
// let result = double1 + float1

// Instead, convert explicitly:
let result = double1 + Double(float1)

3. Type Annotation vs Type Inference in Swift

Swift provides two powerful approaches to handling types in your code: explicit type annotation and automatic type inference. Understanding when to use each makes your code more readable and maintainable.

A. Type Annotation: Being Explicit

Type annotation means explicitly telling Swift what type a variable or constant should be:

// Explicit type annotations
var playerHealth: Double = 100.0
var isGameActive: Bool = true
var highScores: [Int] = [1200, 955, 840]
var userSettings: [String: Any] = [
    "soundEnabled": true,
    "difficulty": "hard"
]

When to use type annotation:

  1. When you want to be crystal clear about your intentions:

    // Making it obvious this should be a Double, not an Int
    var distance: Double = 0
  2. When initializing empty variables:

    // Can't infer type without initial value
    var userName: String
    var currentLevel: Int
  3. When working with complex types:

    // Custom types and protocols
    var gameState: GameState
    var delegate: GameDelegate?

B. Type Inference: Letting Swift Do the Work

Type inference allows Swift to automatically determine the type based on the value you provide:

// Swift automatically infers these types
var score = 42             // Inferred as Int
var playerName = "Alex"    // Inferred as String
var isPlaying = true       // Inferred as Bool
var acceleration = 9.81    // Inferred as Double

Benefits of type inference:

  1. Cleaner, more concise code:

    // Type inference makes this more readable
    let colors = ["red", "green", "blue"]  // [String]
    let temperatures = [72.5, 73.0, 71.8]  // [Double]
  2. Less typing, same type safety:

    // Both approaches are equally type-safe
    let explicitAge: Int = 25
    let inferredAge = 25      // Just as safe, more concise

C. Best Practices and Examples

struct GameCharacter {
    // Use type annotation for empty properties
    var name: String

    // Let Swift infer types when initializing with values
    var health = 100.0
    var inventory = ["potion", "sword"]

    // Explicit typing for clarity with numeric types
    var experience: Double = 0

    // Type annotation for optional values
    var equipment: Equipment?

    // Inferred type for computed properties
    var isAlive {
        health > 0
    }
}

D. Common Gotchas and Tips

  1. Number Types:

    // Be explicit when you need a specific numeric type
    var preciseMeasurement: Double = 100    // Ensures Double
    var simpleCount = 100                   // Infers Int
  2. Collections:

    // Type annotation helps with empty collections
    var scores: [Int] = []
    var cache: [String: Any] = [:]

// Inference works great with populated collections var names = ["Alice", "Bob"] // [String] var heights = [1.72, 1.85, 1.68] // [Double]

3. **Custom Types:**
```swift
class Vehicle {
    // Explicit typing for protocol conformance
    var delegate: VehicleDelegate?

    // Inference for simple properties
    var isRunning = false

    // Annotation for specific requirements
    var speed: Double = 0.0
}

4. Choosing Between Variables and Constants

Understanding when to use variables versus constants isn't just about following rules—it's about designing clear, maintainable, and efficient code. Let's explore how to make these choices strategically in your SwiftUI applications.

A. When to Use Variables (var)

Variables are your dynamic data containers, perfect for values that need to change throughout your app's lifecycle. Think of them as the moving parts of your application:

struct ProfileView: View {
    // User input that changes
    @State private var username = ""
    @State private var isEditing = false

    // Values that update during gameplay
    @State private var score = 0
    @State private var livesRemaining = 3

    // Form and UI state
    @State private var selectedTab = 0
    @State private var searchText = ""
}

Use variables for:

  • User input data such as names, email addresses, and text entries
  • Game scores that track player progress and achievements
  • Form fields where users enter and modify information
  • Toggle states to track UI elements' on/off conditions
  • Counter values like inventory quantities or step counts

B. When to Use Constants (let)

Constants are your guardrails—they represent values that should remain fixed once set. They make your code more predictable and often more performant:

struct GameConfig {
    // Configuration constants
    static let maxPlayers = 4
    static let baseURL = "https://api.game.com"

    // Game rules
    static let minimumAge = 13
    static let maxLives = 3

    // UI configuration
    static let animationDuration = 0.3
    static let cornerRadius: CGFloat = 8
}

Use constants for:

  • Configuration values like server settings and environment variables
  • API endpoints where your backend service URLs need to remain fixed
  • Game rules such as level requirements or winning conditions
  • Fixed UI text including button labels, headers, and static messages
  • Maximum values that set boundaries or limits in your application

C. Combining Variables and Constants

struct GameView: View {
    // Constants - Fixed game rules
    let maxScore = 1000
    let timeLimit = 60
    let bonusMultiplier = 1.5

    // Variables - Dynamic game state
    @State private var currentScore = 0
    @State private var timeRemaining = 60
    @State private var isPlaying = false

    var body: some View {
        VStack {
            Text("Score: \(currentScore)/\(maxScore)")
            Text("Time: \(timeRemaining)s")

            if currentScore >= maxScore {
                Text("You Win!")
            }
        }
    }
}

5. Mastering Swift's Type System

Writing efficient Swift code isn't just about making things work—it's about making them work well. Let's explore key guidelines that will help you write more robust and performant applications.

A. Type Safety Best Practices

Swift's type system is designed to help prevent errors and make your code more reliable. Here's how to leverage it effectively:

struct PlayerStats {
    // Explicit typing for clarity
    let id: UUID
    var score: Int

    // Using type inference appropriately
    let dateJoined = Date()
    var isOnline = false

    // Being specific with numeric types
    var height: Double = 1.85
    var experience: Int = 0
}

Key principles to follow:

  • Always be clear about what type you need
  • Let Swift infer types when it's obvious
  • Use explicit types when you want to be specific
  • Pay attention to type mismatch errors

B. Memory and Performance Optimization

Smart memory management leads to better app performance:

class GameEngine {
    // Constants for configuration (better performance)
    let maxPlayers: Int
    let gameRules: GameRules

    // Variables only for changing state
    private var currentLevel = 1
    private var activePlayers: [Player] = []

    // Consider scope
    func playLevel() {
        let levelDuration = 60 // Local constant
        var timeRemaining = levelDuration // Local variable
        // ... level logic
    }
}

Best practices:

  • Use constants whenever possible for better performance
  • Only use variables when values need to change
  • Consider scope and lifetime of your variables

6. Conclusion

Understanding variables and constants is fundamental to Swift programming. By using them appropriately, you can write safer, more maintainable code. Remember: start with constants (let) by default, and only use variables (var) when you need values to change.

Next Steps

  • Practice identifying when to use variables vs constants
  • Experiment with different types in your code
  • Review existing code for proper usage
  • Learn about more complex type systems

Learn with videos and source files. Available to Pro subscribers only.

Purchase includes access to 50+ courses, 320+ premium tutorials, 300+ hours of videos, source files and certificates.

BACK TO

Comments Documentation Waypoints

READ NEXT

Strings and Interpolation

Templates and source code

Download source files

Download the videos and assets to refer and learn offline without interuption.

check

Design template

check

Source code for all sections

check

Video files, ePub and subtitles

Videos

Assets

1

Building Your iOS Development Foundation

Master the fundamentals of Swift programming with hands-on examples designed for beginners and experienced developers alike

2

SwiftUI Print Debugging

Print debugging: Unlock the invisible processes with strategic print statements that illuminate state changes, view lifecycles and data flow

18:04

3

Comments Documentation Waypoints

Transform your code from mysterious instructions to a comprehensive narrative with strategic comments that explain the why

22:02

4

Variables and Constants

Learn when and how to use variables and constants to write safer, more efficient SwiftUI code

11:37

5

Strings and Interpolation

Learn essential string operations in Swift: Build better iOS apps with efficient text handling techniques

13:22

6

Swift Operators: The Foundation of SwiftUI Logic

Building powerful iOS apps through the language of operations

5:34

7

Swift Unary Operators

Mastering the elegant simplicity of unary operators for cleaner, more expressive SwiftUI code that transforms your UI with minimal syntax

15:00

8

Swift Binary Operators

Master the two-operand symbols that transform complex interface logic into concise, readable declarations

3:36

9

Arithmetic Operators

Learn how to implement and optimize arithmetic operations in SwiftUI, from basic calculations to complex mathematical interfaces

6:11

10

If-Else and Comparison Operators

Building Dynamic SwiftUI: Mastering If-Else and Comparison Operators

12:32

11

Logical Operators

Master SwiftUI's logical operators: Building intelligent iOS apps with robust decision-making systems

6:03

12

Ternary Operators

Use the power of Swift's ternary conditional operator to create dynamic, responsive interfaces with minimal code in SwiftUI

6:22

13

Blocks and Scope

A comprehensive guide to writing clean, organized code through proper variable management and state control

10:22

14

Swift Collections: Arrays, Sets, and Dictionaries Overview

Organize Your Data Effectively: Learn How to Choose and Optimize the Perfect Collection Type for Your SwiftUI Applications

7:00

15

Swift Arrays

Organize, transform, and display your data with Swift's most essential collection structure

8:54

16

Swift Sets

Mastering Unique Collections with Fast Lookups and Powerful Operations

11:03

17

Swift Dictionaries

Master Swift's key-value collection type with practical examples for efficient data storage, retrieval, and transformation in SwiftUI apps

18

For-Loops and Range

For-Loops and Ranges: Learn how to repeat code efficiently and work with sequences of numbers in Swift

19

Optionals

Optionals in Swift: Understanding Swift's Safety System for Handling Missing Values

20

Functions

Functions in Swift: Building Reusable Code Blocks to Organize and Streamline Your App

Meet the instructor

We all try to be consistent with our way of teaching step-by-step, providing source files and prioritizing design in our courses.

Sourasith Phomhome

UI Designer

Designer at Design+Code

icon

20 courses - 78 hours

course logo

Master Agentic Workflows

In this course, you’ll learn how to add agents to your workflows. An agent workflow is more than just a simple automation. Instead of following a fixed script, agents can make decisions, adjust to changes, and figure out the best way to complete a task. We’ll start by exploring what MCP servers are and all the new possibilities they bring. Then, we’ll dive into agentic frameworks that make it easy to build flexible, helpful agents that can take care of your everyday tasks.

2 hrs

course logo

Design Multiple Apps with Figma and AI

In this course, you’ll learn to design multiple apps using Figma and AI-powered tools, tackling a variety of real-world UI challenges. Each week, a new episode will guide you through a different design, helping you master essential UI/UX principles and workflows

4 hrs

course logo

SwiftUI Fundamentals Handbook

A comprehensive guide to mastering Swift programming fundamentals, designed for aspiring iOS developers. This handbook provides a structured approach to learning Swift's core concepts, from basic syntax to advanced programming patterns. Through carefully sequenced chapters, readers will progress from essential programming concepts to object-oriented principles, building a solid foundation for SwiftUI development. Each topic includes practical examples and clear explanations, ensuring a thorough understanding of Swift's capabilities. This handbook serves as both a learning resource and a reference guide, covering fundamental concepts required for modern iOS development. Topics are presented in a logical progression, allowing readers to build their knowledge systematically while gaining practical programming skills.

2 hrs

course logo

Design and Code User Interfaces with Galileo and Claude AI

In this course, you’ll learn how to use AI tools to make UI/UX design faster and more efficient. We’ll start with Galileo AI to create basic designs, providing a solid foundation for your ideas. Next, we’ll refine these designs in Figma to match your personal style, and finally, we’ll use Claude AI to turn them into working code—eliminating the need for traditional prototyping.

4 hrs

course logo

Build a React Native app with Claude AI

This comprehensive course explores the integration of cutting-edge AI tools into the React Native development workflow, revolutionizing the approach to mobile application creation. Participants will learn to leverage AI-powered platforms such as Claude and Locofy to expedite coding processes, enhance problem-solving capabilities, and optimize productivity.

14 hrs

course logo

Design and Prototype for iOS 18

Design and Prototype for iOS 18 is an immersive course that equips you with the skills to create stunning, user-friendly mobile applications. From mastering Figma to understanding iOS 18's latest design principles, you'll learn to craft two real-world apps - a Car Control interface and an AI assistant.

3 hrs

course logo

Master Responsive Layouts in Figma

Creating responsive layouts is a must-have skill for any UI/UX designer. With so many different devices and screen sizes, designing interfaces that look great and work well on all platforms is necessary. Mastering this skill will make you stand out in the field. In this course, we'll start from scratch to create this beautiful design using Figma. You'll learn how to make layouts that are easy to use and work well on any device. We'll cover key concepts and tools to help you master responsive design in Figma.

2 hrs

course logo

UI UX Design with Mobbin and Figma

Mobbin is a powerful tool for UI/UX designers seeking inspiration and innovative design solutions. This platform offers a vast collection of real-world mobile app designs, providing a treasure trove of UI elements and layouts.

2 hrs

course logo

3D UI Interactive Web Design with Spline

Learn to create 3D designs and UI interactions such as 3D icons, UI animations, components, variables, screen resize, scrolling interactions, as well as exporting, optimizing, and publishing your 3D assets on websites

3 hrs

course logo

Design and Prototype for iOS 17 in Figma

Crafting engaging experiences for iOS 17 and visionOS using the Figma design tool. Learn about Figma's new prototyping features, Dev Mode, variables and auto layout.

6 hrs

course logo

Design and Prototype Apps with Midjourney

A comprehensive course on transforming Midjourney concepts into interactive prototypes using essential design techniques and AI tools

8 hrs

course logo

iOS Design with Midjourney and Figma

Learn the fundamentals of App UI design and master the art of creating beautiful and intuitive user interfaces for mobile applications

1 hrs

course logo

UI Design for iOS, Android and Web in Sketch

Create a UI design from scratch using Smart Layout, Components, Prototyping in Sketch app

1 hrs

course logo

UI Design a Camera App in Figma

Design a dark, vibrant and curvy app design from scratch in Figma. Design glass icons, lens strokes and realistic buttons.

1 hrs

course logo

UI Design for iOS 16 in Sketch

A complete guide to designing for iOS 16 with videos, examples and design files

3 hrs

course logo

Prototyping in Figma

Learn the basics of prototyping in Figma by creating interactive flows from custom designs

1 hrs

course logo

UI Design Quick Websites in Figma

Learn how to design a portfolio web UI from scratch in Figma

1 hrs

course logo

UI Design Android Apps in Figma

Design Android application UIs from scratch using various tricks and techniques in Figma

2 hrs

course logo

UI Design Quick Apps in Figma

Design application UIs from scratch using various tricks and techniques in Figma

12 hrs

course logo

Figma Handbook

A comprehensive guide to the best tips and tricks in Figma

6 hrs