Menu
CoddyTech

Structs and Independent Copies

Lesson 26 of 48 in Coddy's Swift for Kotlin Developers course.

A Kotlin data class still has reference semantics: assigning one variable to another shares the same instance, and copy must be requested explicitly. Swift structs are value types, so assignment creates an independent value automatically. Methods that change stored properties must be marked mutating, and callers need a var binding for that value. A struct can contain reference-type properties, so a value copy does not promise a recursive deep clone of every object reachable from it. The example reflects one coordinate of a copied point. It uses a Kotlin data-class copy and a Swift struct assignment to preserve the original coordinates.

Kotlin

data class Point(var x: Int, val y: Int)
fun main() {
    val original = Point(3, 4)
    val reflected = original.copy()
    reflected.x = -reflected.x
    println("${original.x} ${reflected.x}")
}

Swift

struct Point { var x: Int; let y: Int }
let original = Point(x: 3, y: 4)
var reflected = original
reflected.x = -reflected.x
print(original.x, reflected.x)
challenge icon

Challenge

Easy

Implement value type Score with stored points: Int, init(points:), and mutating award(_ amount: Int) adding amount. Input is initial points and award, each 0 through 1000. Copy the original, award only the copy, and output original and copy points separated by a space.

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 Score.swift, 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 original = Score(points: 13); var copy = original; copy.award(6); copy.award(2); return original.points == 13 && copy.points == 21
}
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 Kotlin Developers

Practice on your own: Swift playground