Classes and Shared Identity
Lesson 28 of 48 in Coddy's Swift for JavaScript Developers course.
JavaScript class instances are objects with shared identity, and strict equality of these object references tests that identity. Swift classes also share instance identity under assignment, using ===. Swift == is a separate equality operation requiring applicable conformance rather than a universal identity comparison.
The source const and target let bindings prevent rebinding but permit allowed instance mutation. Changing the shared title is visible through both names. Swift classes need initialization that establishes their stored properties and do not receive every struct-style memberwise initializer automatically. Use structs when independent value evolution is the desired model.
JavaScript
Complete JavaScript console program:
main.js
class Tab { constructor(title) { this.title = title; } }
const left = new Tab("draft");
const right = left;
right.title = "final";
console.log(left.title, left === right);
Swift
Complete program; compile the listed files together:
Tab.swift
import Foundation
final class Tab {
var title: String
init(title: String) { self.title = title }
}main.swift
import Foundation
let left = Tab(title: "draft")
let right = left
right.title = "final"
print(left.title, left === right)Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for JavaScript 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 Rules3Control Flow
Switch and PatternsEnums as Finite ChoicesFor Loops and RangesWhile and Repeat LoopsRecap: Sequence Scan6Values and References
Structs and Independent CopiesStored and Computed PropertiesClasses and Shared IdentityARC and Weak ReferencesRecap: Value BasketPractice on your own: Swift playground