Menu
CoddyTech

Inout and Exclusive Access

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

A Luau numeric argument initializes a local parameter. Reassigning that parameter does not reassign the caller's variable, so attempts stays four. A table argument can expose shared table mutation, but rebinding the parameter to a new table still does not replace the caller's local.

Swift inout explicitly requests mutation of caller storage, and & marks the mutable argument at the call. Exclusive access rules prevent incompatible overlapping accesses while that update is in progress. The target resets attempts itself to zero; returning a replacement value would be a different API design.

Luau

Complete Luau console program:

main.luau

local function reset(value: number)
  value = 0
end
local attempts = 4
reset(attempts)
print(attempts)

Swift

Complete program; compile the listed files together:

Functions.swift

import Foundation
func reset(_ value: inout Int) { value = 0 }

main.swift

import Foundation
var attempts = 4
reset(&attempts)
print(attempts)
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 Luau Developers

Practice on your own: Swift playground