Inout and Exclusive Access
Lesson 17 of 48 in Coddy's Swift for Rust Developers course.
Rust &mut grants an exclusive mutable borrow governed by borrowing rules and lifetimes. Swift inout similarly makes caller mutation explicit, with & at the call, but its contract is temporary read-modify-write access rather than a general Rust reference type. Swift can support computed-property writeback, and its exclusivity checks prohibit overlapping conflicting accesses. Do not assume an inout parameter may escape or be stored as an ordinary alias. Both functions double a mutable integer in caller storage. Passing the same variable as two simultaneously active mutable arguments is not made valid merely because a small example appears harmless.
Rust
fn double(value: &mut i32) { *value *= 2; }
fn main() {
let mut width = 6;
double(&mut width);
println!("{}", width);
}
Swift
func double(_ value: inout Int) { value *= 2 }
var width = 6
double(&width)
print(width)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 Rust 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