Menu
CoddyTech

Arrays Have Value Semantics

Lesson 19 of 48 in Coddy's Swift for R Developers course.

Ordinary R lists and vectors use copy-on-modify behavior. Assigning rows and then replacing a nested numeric vector in copy preserves the original list's value. Environments stored inside a list are different: their shared reference identity can expose mutation through multiple containers.

Swift Array has value semantics. Assigning the nested array preserves independent observable values, so changing an inner array in the copy leaves rows unchanged. Copy-on-write is an implementation optimization, not a promise of shared mutation. Arrays holding class instances still contain references to those instances.

The original R row remains one and the Swift original remains [[1]]. Both copied outer collections contain two elements. This agreement comes from the chosen value-like components, not from a promise that every R object or every Swift element is deeply cloned.

Complete R comparison program:

rows <- list(c(1L))
copy <- rows
copy[[1L]] <- c(copy[[1L]], 2L)
copy[[2L]] <- 3L
cat(paste(rows[[1L]], collapse = " "), "\n", length(copy), "\n", sep = "")

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 icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for R Developers

Practice on your own: Swift playground