Menu
CoddyTech

Inout and Exclusive Access

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

C# ref makes a parameter refer to caller storage. Swift inout specifies a read-modify-write access to a caller value, with & at the call site. Think in terms of copying a value in and writing it back when the call finishes; do not rely on an implementation always passing a raw pointer. Swift requires exclusive access during mutation, so overlapping access to the same variable can be rejected. A computed property may participate through its getter and setter. This example toggles a Boolean setting. Mutating one value is different from sorting two values in place in the exercise.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;
static class Settings { public static void Toggle(ref bool value) { value = !value; } }

class Program
{
    static void Main()
    {
        bool muted = false;
        Settings.Toggle(ref muted);
        Console.WriteLine(muted ? "muted" : "audible");
    }
}

Swift

Complete program file: Functions.swift.

func toggle(_ value: inout Bool) { value.toggle() }

Complete program file: main.swift.

var muted = false
toggle(&muted)
print(muted ? "muted" : "audible")
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 C# Developers

Practice on your own: Swift playground