Arrays Have Value Semantics
Lesson 19 of 48 in Coddy's Swift for JavaScript Developers course.
JavaScript Array assignment normally aliases one object. Spread creates a new outer array, but object-valued elements remain references to shared objects. These number elements avoid that extra layer, so replacing and appending in the source copy leaves the original unchanged.
Swift Array assignment provides independent observable value semantics without requiring explicit spread. Copy-on-write may share internal storage until mutation, but that does not change the value contract. Arrays containing class references can still share their referenced instances, so changing a pointee differs from replacing an element.
JavaScript
Complete JavaScript console program:
main.js
const original = [5, 8];
const copy = [...original];
copy[0] = 9;
copy.push(2);
console.log(original.join(":"), copy.join(":"));
Swift
Complete program; compile the listed files together:
main.swift
import Foundation
let original = [5, 8]
var copy = original
copy[0] = 9
copy.append(2)
print(original.map(String.init).joined(separator: ":"), copy.map(String.init).joined(separator: ":"))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 JavaScript 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