Arrays Have Value Semantics
Lesson 19 of 48 in Coddy's Swift for C Developers course.
C arrays cannot be assigned as whole standalone array objects, and in many expressions an array converts to a pointer to its first element. The source alias therefore refers to the original storage. Swift Array assignment preserves independent observable value semantics when one copy replaces an element.
The source writes the same C array through a pointer, while Swift changes only its second array value. C needs an explicit element or byte copy for independent array storage. Swift may share backing storage until mutation, but that optimization does not change its value contract. Class-reference elements can still be shared between Swift arrays.
C: complete program
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(void) {
int original[] = {4, 6};
int *alias = original;
alias[0] = 9;
printf("%d %d\n", original[0], alias[0]);
return 0;
}
Swift: complete program
main.swift
import Foundation
let original = [4, 6]
var copy = original
copy[0] = 9
print("\(original[0]) \(copy[0])")Replacing an array element is distinct from mutating an object referenced by that element. Value semantics do not promise recursively cloning class instances.
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 C 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