liveBook · Manning

Inout

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

inout is a Swift parameter modifier that allows a function to modify the caller's original variable.

inout lets a Swift function modify the caller’s original variable instead of a temporary copy. Pass the argument with &, and changes persist after the function returns. section 2.2

Marking a maze path

func markMaze(_ maze: inout Maze, path: [MazeLocation], start: MazeLocation, goal: MazeLocation) { ... }\n\nmarkMaze(&maze, path: path, start: start, goal: goal)\n\nThe function marks path cells and replaces the start and goal cells in the original maze, so printing maze afterward displays the solution. section 2.2

// A Cell represents the status of a grid location in the maze
enum Cell: Character {
    case Empty = "O"
    case Blocked = "X"
    case Start = "S"
    case Goal = "G"
    case Path = "P"
}

typealias Maze = [[Cell]]

Use the Maze and Cell definitions to see the mutable grid that markMaze updates through inout. section 2.2

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Explains caller-visible mutation, temporary-copy avoidance, persistence after return, and ampersand call syntax.
Examples
Demonstrates markMaze updating a Maze and a subsequent printMaze displaying the persisted path.
What it assumes
Assumes functions, variables, and a Maze type while teaching how argument mutation persists beyond function scope.
What you can do after
Apply it via Swift functions that mutate caller-owned variables and invoke those functions with &.
How it connects
Connects inout with functions, mutable variables, value copying, and call-by-reference analogies.

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.