Menu
CoddyTech

Inout and Exclusive Access

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

Ruby passes object references as values. Rebinding the local parameter would not rebind the caller, but String#replace mutates the shared mutable string object. That makes the change visible through draft without a special call-site marker. A frozen string would reject this mutation.

Swift inout makes an update to caller-owned storage explicit. The parameter is marked inout and the call uses & with a mutable variable. Exclusive access rules restrict overlapping reads and writes to that storage during the access; it is not a freely aliasable general-purpose pointer.

Both examples clear the caller-visible text, but the mechanisms differ. Swift String has value semantics, so inout explicitly grants temporary mutable access to draft and & marks that access at the call. Do not treat shared Ruby object mutation as a general permission for overlapping Swift inout accesses.

Complete Ruby comparison program:

def clear_text(text)
  text.replace("")
end
draft = "memo"
clear_text(draft)
puts draft.length

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 Ruby Developers

Practice on your own: Swift playground