Menu
CoddyTech

Inout and Exclusive Access

Lesson 17 of 48 in Coddy's Swift for Python Developers course.

Python passes object references into functions. Rebinding an integer parameter cannot replace the caller name, so a function often returns a new value. Mutating a passed list is different because caller and parameter can refer to the same list.

Swift inout grants a function temporary write access to a caller variable. The call uses & before that variable. Think of it as receiving the value and writing the result back, rather than assuming a permanent pointer alias. Swift enforces exclusive access: overlapping reads or writes during that access can be invalid.

The example clears a draft string through an inout parameter. A constant cannot be supplied because it cannot receive an updated value. In the exercise, the two caller variables must be distinct for their simultaneous write accesses.

Complete Python comparison program:

def clear(text):
    text = ""
    return text
draft = "memo"
print(len(clear(draft)), len(draft))

Complete Swift comparison program, compiled from these files:

Functions.swift

func clear(_ text: inout String) {
    text = ""
}

main.swift

var draft = "memo"
clear(&draft)
print(draft.count)
challenge icon

Challenge

Easy

Implement order(_:_:) using two inout integers: leave the smaller value in first and larger in second. Input has two integers -1000 through 1000; output their ordered values separated by one space. Callers supply distinct variables.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
var a = 9; var b = 2; order(&a, &b); guard a == 2 && b == 9 else { return false }; order(&a, &b); return a == 2 && b == 9
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Python Developers

Practice on your own: Swift playground