Menu
CoddyTech

Structs and Independent Copies

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

GDScript user-defined classes have reference identity; assigning an instance to another variable shares the same object. Built-in value types do not turn such a class into a Swift struct. Swift struct assignment preserves independent value state for its stored value properties.

Swift stored properties use let or var, and eligible structs receive memberwise initialization. A method that updates stored properties is marked mutating and requires a mutable receiver. A struct field containing a class reference still shares that referenced object when copied.

The source changes one shared Heading instance through two names. The target changes only its second Heading value, leaving north in the first. Choose an explicit copy policy if source object independence is needed.

Complete GDScript comparison program:

extends SceneTree
class Heading:
    var direction: String
    func _init(value: String):
        direction = value
    func turn_west() -> void:
        direction = "west"

func _init():
    var first = Heading.new("north")
    var second = first
    second.turn_west()
    print(first.direction, " ", second.direction)
    quit()

Complete Swift comparison program, compiled from these files:

Heading.swift

struct Heading {
    var direction: String
    mutating func turnWest() { direction = "west" }
}

main.swift

let first = Heading(direction: "north")
var second = first
second.turnWest()
print(first.direction, second.direction)
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 GDScript Developers

Practice on your own: Swift playground