Menu
CoddyTech

Classes and Shared Identity

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

Go pointers can share one struct instance and compare whether they identify the same object. Swift class references supply shared identity directly, using === for identity. Swift == is a separate equality contract and is not automatically the identity test for every class.

The source intentionally uses a pointer rather than copying a Document struct value. Both aliases observe its closure. Swift let fixes the reference binding but does not prevent permitted instance mutation, so the target class can close through either alias.

Go: complete program

document.go

package main
type Document struct { Open bool }
func (document *Document) Close() { document.Open = false }

main.go

package main
import (
    "fmt"
)

func main() {
first := &Document{Open: true}
    second := first
    second.Close()
    fmt.Println(first.Open, first == second)
}

Swift: complete program

Document.swift

import Foundation
final class Document {
    private(set) var open = true
    func close() { open = false }
}

main.swift

import Foundation
let first = Document()
let second = first
second.close()
print("\(first.open) \(first === second)")

Choose Go value copying or pointer sharing deliberately when translating to a Swift struct or class. A constant class binding is not a deep-immutability promise.

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

Practice on your own: Swift playground