Menu
CoddyTech

Arrays Have Value Semantics

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

Go slices describe a region of an underlying array. Assigning a slice copies its descriptor, so both slices can still access the same elements. Go fixed arrays instead copy their elements on assignment. Swift Array has value semantics when a copied array replaces an element.

The source deliberately shares slice backing storage and therefore changes the original first element. Swift changes only the second array value. Go needs an explicit copy into separate storage for that behavior. Swift copy-on-write may share physical storage internally without exposing the same value-mutation aliasing.

Go: complete program

main.go

package main
import (
    "fmt"
)

func main() {
original := []int{4, 6}
    copied := original
    copied[0] = 9
    fmt.Println(original[0], copied[0])
}

Swift: complete program

main.swift

import Foundation
let original = [4, 6]
var copy = original
copy[0] = 9
print("\(original[0]) \(copy[0])")

Copying a container does not necessarily clone objects referenced by its elements. Also assess Go append and capacity behavior rather than assuming every append preserves the same backing array.

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

Practice on your own: Swift playground