Menu
CoddyTech

Classes and Shared Identity

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

GDScript Object-derived instances and Swift class instances preserve shared identity under ordinary assignment. Mutating one instance through an alias is visible through the other reference. Swift === checks class identity, while == requires a separate applicable equality contract.

Swift class initialization must establish stored properties, and classes do not automatically receive every struct-style memberwise initializer. A let binding fixes which object the reference names but permits mutable instance state to change. Class methods do not use the mutating modifier needed for Swift value types.

The source and target rename the same document through an alias. This sharing is intentional; choose a struct when the desired Swift model instead needs independently evolving value state.

Complete GDScript comparison program:

extends SceneTree
class Document:
    var title: String
    func _init(value: String):
        title = value

func _init():
    var first = Document.new("notes")
    var alias = first
    alias.title = "archive"
    print(first.title, " ", first == alias)
    quit()

Complete Swift comparison program, compiled from these files:

Document.swift

final class Document {
    var title: String
    init(title: String) { self.title = title }
}

main.swift

let first = Document(title: "notes")
let alias = first
alias.title = "archive"
print(first.title, first === alias)
challenge icon

Challenge

Easy

Implement Counter, a reference type with init(_ value: Int), read-only-to-callers value, and increment() adding one. Input is initial value -100 through 100 then count 0 through 20. Alias a counter, increment through the alias count times, and output the original value.

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 Counter.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 a = Counter(5); let alias = a; let separate = Counter(5); alias.increment(); alias.increment(); return a === alias && a.value == 7 && separate.value == 5
}
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