Bindings and Mutation
Lesson 2 of 48 in Coddy's Swift for Rust Developers course.
Rust bindings are immutable by default, and mut permits changing a binding or mutating its owned value through the appropriate API. Assigning a Vec normally moves ownership; clone explicitly duplicates its elements. Swift let and var choose binding mutability, but Array assignment preserves independent value behavior without an explicit clone call. Its copy-on-write storage optimization does not expose shared array mutation. Both programs retain two original entries and append a third to the copy. Rust Copy types, explicit Clone implementations and shared smart pointers have different copying contracts, so do not map every Rust assignment to one universal ownership behavior in Swift. Both languages retain static types after inference.
Rust
fn main() {
let original = vec![2, 4];
let mut copy = original.clone();
copy.push(6);
println!("{} {}", original.len(), copy.len());
}
Swift
let original = [2, 4]
var copy = original
copy.append(6)
print(original.count, copy.count)Challenge
EasyImplement offset(_ value: Int) -> Int: add 7 to a value. Input is one integer from -1000 through 1000; output is the resulting integer.
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 {
return offset(31) == 38 && offset(-8) == -1 && offset(31) == 38
}
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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Rust Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground