Arrays Have Value Semantics
Lesson 19 of 48 in Coddy's Swift for Python Developers course.
Python list assignment creates another reference to the same list. A slice or copy() creates a shallow list copy, leaving contained objects shared. The example shows that a nested list remains shared even after copying its outer list.
Swift Array is a value type. Assignment preserves independent observable array values; storage may be shared internally until mutation. Arrays of arrays therefore retain independent nested array values. This does not imply a deep clone of class instances stored inside an array: those elements still refer to their original objects.
Use a mutable binding for operations such as append and indexed assignment. An empty literal may need an element type annotation. The exercise rearranges an array; plan the empty case before accessing any element.
Complete Python comparison program:
rows = [[1]]
copy = rows.copy()
copy[0].append(2)
copy.append([3])
print(rows)
print(len(copy))Complete Swift comparison program, compiled from these files:
main.swift
let rows = [[1]]
var copy = rows
copy[0].append(2)
copy.append([3])
print(rows)
print(copy.count)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 Python 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