Menu
CoddyTech

Arrays Have Value Semantics

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

C# arrays and List<T> are reference types: assigning a local creates another reference to the same collection. Swift Array has value semantics: changing one array value does not change a separately assigned copy. Copy-on-write may share storage internally until mutation, but the observable value behavior is the guarantee. The guarantee is not a deep copy of reference-type elements. The example appends a new item to one collection and compares lengths, deliberately showing different results across languages. If elements are classes, both array values can still refer to the same objects. Choose a value or reference model explicitly when porting collection-owning types.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var original = new List<int> { 2, 4 };
        var copy = original;
        copy.Add(8);
        Console.WriteLine(original.Count + " " + copy.Count);
    }
}

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