Inout and Exclusive Access
Lesson 17 of 48 in Coddy's Swift for Java Developers course.
Java passes every argument by value, including object references. Assigning a new value to a primitive parameter does not change the caller variable. Swift inout gives a function temporary read-write access to caller storage, written with & at the call.
The examples reset a calibration reading. Java returns a replacement value and the caller assigns it. Swift writes back through the inout parameter. During that access the same storage cannot be used through overlapping conflicting accesses; inout is not a general pointer escape mechanism.
Java: complete program
Main.java
import java.util.*;
import java.util.function.*;
public class Main {
static int reset(int reading) { reading = 0; return reading; }
public static void main(String[] args) throws Exception {
int reading = 9;
reading = reset(reading);
System.out.println(reading);
}
}Swift: complete program
Functions.swift
import Foundation
func reset(_ reading: inout Int) { reading = 0 }main.swift
import Foundation
var reading = 9
reset(&reading)
print(reading)Do not pass the same variable to two inout parameters in one call. Swift exclusive-access rules prohibit overlapping modifications even if the function body looks harmless.
Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Java Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground