Inheritance and Overrides
Lesson 37 of 48 in Coddy's Swift for Lua Developers course.
Lua can model prototype-style delegation with __index. A missing field on this instance is looked up through QuietVoice, whose own fallback is Voice. Defining sound on QuietVoice supplies the chosen behavior; Lua has no built-in class declaration or override keyword enforcing a matching superclass signature.
Swift classes support a single superclass, and a replacing method is marked override. Dynamic dispatch uses the instance's implementation even through a superclass-typed reference. final can prohibit further overriding or subclassing. Structs do not inherit implementation from other structs.
Both examples select the quiet voice, but their object models differ. Treat metatable delegation as source behavior to model, not syntax to copy literally. Protocols and composition often express reusable behavior without requiring a Swift class hierarchy.
Complete Lua comparison program:
local Voice = {}
function Voice:sound() return "ping" end
local QuietVoice = setmetatable({}, {__index = Voice})
function QuietVoice:sound() return "hush" end
local voice = setmetatable({}, {__index = QuietVoice})
print(voice:sound())
Complete Swift comparison program, compiled from these files:
Voice.swift
class Voice { func sound() -> String { "ping" } }QuietVoice.swift
final class QuietVoice: Voice { override func sound() -> String { "hush" } }main.swift
let voice: Voice = QuietVoice()
print(voice.sound())Challenge
EasyImplement class Rate with init() and fee(units: Int) -> Int returning twice units. Implement subclass RushRate, overriding fee to add 5 to the base fee. Input is base or rush then units 0 through 100. Select an instance through a Rate reference and output its fee.
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 Rate.swift, RushRate.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 r: Rate = RushRate(); return r.fee(units: 7) == 19 && Rate().fee(units: 7) == 14 && r.fee(units: 0) == 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 Lua 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 Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog Merge8Designing Types
Inheritance and OverridesComposition Through a PolicyAccess Control and InvariantsEnums with Associated ValuesFailable InitializationRecap: Booking LedgerPractice on your own: Swift playground