Menu
CoddyTech

Arrays Have Value Semantics

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

GDScript Array assignment shares the same container. duplicate() creates a shallow array copy by default, so nested arrays still refer to the same nested containers. The example modifies a nested array through its copied outer array, which also changes the original nested data.

Swift Array has value semantics, including when its elements are themselves Array values. The target copied nested array can evolve without changing rows. Internal copy-on-write storage sharing is an optimization rather than observable aliasing of value updates.

Neither model automatically deep-clones every class instance stored in a collection. Distinguish copying a container, copying nested value containers and sharing object references before choosing an adaptation.

Complete GDScript comparison program:

extends SceneTree

func _init():
    var rows = [[1]]
    var copied = rows.duplicate()
    copied[0].append(2)
    copied.append([3])
    print(rows)
    print(copied.size())
    quit()

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 GDScript Developers

Practice on your own: Swift playground