Menu
CoddyTech

Inout and Exclusive Access

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

Ordinary assignment inside an R function creates or changes a local binding. Reassigning the text parameter does not rebind draft in the caller. Environments can expose reference mutation, and superassignment searches enclosing environments, but neither is a direct equivalent of a checked temporary inout access.

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.

The R function returns a cleared string while the caller retains memo. Swift clear(&draft) updates the caller's variable explicitly. Prefer returning a replacement when that is the source API's intended contract, and use inout only for the required mutable-storage API.

Complete R comparison program:

clear_text <- function(text) {
  text <- ""
  text
}
draft <- "memo"
cat(nchar(clear_text(draft)), nchar(draft), sep = " ")
cat("\n")

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

Practice on your own: Swift playground