Arrays Have Value Semantics
Lesson 19 of 48 in Coddy's Swift for Java Developers course.
Java arrays and ArrayList objects are reference types, so assignment aliases the same container. Swift Array has value semantics: assigning an array produces a value whose later element replacement does not change the original array.
The examples deliberately contrast aliasing and value copying. Java would need an explicit array copy to isolate the replacement. Swift may share storage internally until mutation, but copy-on-write does not change the observable value behavior. If elements are class references, copying the array still shares those referenced objects.
Java: complete program
Main.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) throws Exception {
int[] original = {4, 6};
int[] copy = original;
copy[0] = 9;
System.out.println(original[0] + " " + copy[0]);
}
}Swift: complete program
main.swift
import Foundation
let original = [4, 6]
var copy = original
copy[0] = 9
print("\(original[0]) \(copy[0])")Value semantics for an array do not promise a recursive clone of every object reachable from its elements. Distinguish replacing an element from mutating the object that an element references.
Challenge
EasyImplement rotated(_:): return a new array moving the first element to the end. Empty and one-element arrays are unchanged. Input has 0 through 50 integers -100 through 100. Output the rotated values separated by single spaces; an empty result is a blank line.
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 {
let a = [8,3,2]; return rotated(a) == [3,2,8] && a == [8,3,2] && rotated([]) == []
}
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 Java 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