Menu
CoddyTech

Arrays Have Value Semantics

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

Copying a C++ std::vector copies its elements into an independent vector value, while binding auto& would instead alias the same container. Swift Array similarly promises independent observable value semantics, often using copy-on-write internally. Both examples append only to the second container. Neither operation necessarily deep-copies objects referenced by pointer-like elements: vector<shared_ptr<T>> and Swift arrays of class references can still share their underlying instances. Distinguish changing the container from changing a pointee. C++ iterator invalidation after reallocation is also a separate issue from Swift value semantics and should be assessed when translating stored views.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>

int main() {
std::vector<int> original{2, 4};
    auto copy = original;
    copy.push_back(8);
    std::cout << original.size() << ' ' << copy.size() << '\n';
}

Swift

Complete program file: main.swift.

let original = [2, 4]
var copy = original
copy.append(8)
print("\(original.count) \(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 C++ Developers

Practice on your own: Swift playground