Arrays Have Value Semantics
Lesson 19 of 48 in Coddy's Swift for Kotlin Developers course.
Kotlin List is a read-only interface, not a guarantee that no other reference can change the underlying collection. Kotlin MutableList explicitly exposes mutating operations. Swift Array is instead a value type: copying it preserves independent observable values. Storage may use copy-on-write internally, which avoids eager copying without changing the language-level result. Array indices are integer offsets. On the JVM, an out-of-range Kotlin index throws an exception. An out-of-range Swift Array subscript traps, so validate an index before accessing it. Use first and last when an empty array is possible; Swift returns optionals for those properties. Removing an element changes later indices, so a loop that deletes elements needs a deliberate iteration strategy.
Kotlin
fun main() {
val original = mutableListOf(8, 9)
val copy = original.toMutableList()
copy.removeAt(0)
println(original.joinToString(" "))
println(copy.joinToString(" "))
}Swift
let original = [8, 9]
var copy = original
copy.remove(at: 0)
print(original.map(String.init).joined(separator: " "))
print(copy.map(String.init).joined(separator: " "))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 Kotlin 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