Menu
CoddyTech

Inout and Exclusive Access

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

Kotlin function parameters cannot be reassigned, and assigning a caller variable through a parameter is not a supported mechanism. Swift inout explicitly allows a function to update a caller variable. The call uses an ampersand before that variable, and the variable must be declared with var. Think in terms of reading the value into the operation and writing the result back, rather than assuming an ordinary shared reference. Swift enforces exclusive access during mutation: passing the same variable to two overlapping inout parameters is invalid. The example applies a numerical transformation; a Kotlin function expresses the corresponding update by returning a value.

Kotlin

fun doubled(value: Int): Int = value * 2
fun main() {
    var width = 6
    width = doubled(width)
    println(width)
}

Swift

func double(_ value: inout Int) { value *= 2 }
var width = 6
double(&width)
print(width)
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 Kotlin Developers

Practice on your own: Swift playground