Inheritance and Overrides
Lesson 37 of 48 in Coddy's Swift for C Developers course.
C has no language-level class inheritance, but a callback table can select behavior dynamically. Swift classes support single inheritance, with override required when replacing inherited behavior and final preventing further subclassing or overriding. Swift structs use conformance and composition instead of class inheritance.
The source calls a supplied greeting function, while the Swift superclass-typed reference dispatches to its subclass override. These mechanisms can express similar runtime choices without having identical object layouts or initialization rules. Swift subclass initialization must establish stored state and delegate appropriately.
C: complete program
greeter.h
#ifndef GREETER_H
#define GREETER_H
typedef struct { const char *(*greeting)(void); } Greeter;
#endif
formal.h
#ifndef FORMAL_H
#define FORMAL_H
#include "greeter.h"
static const char *formal_greeting(void) { return "Good day"; }
static Greeter formal_greeter(void) { return (Greeter){formal_greeting}; }
#endif
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "formal.h"
int main(void) {
Greeter greeter = formal_greeter();
puts(greeter.greeting());
return 0;
}
Swift: complete program
Greeter.swift
import Foundation
class Greeter {
func greeting() -> String { "Hi" }
}FormalGreeter.swift
import Foundation
final class FormalGreeter: Greeter {
override func greeting() -> String { "Good day" }
}main.swift
import Foundation
let greeter: Greeter = FormalGreeter()
print(greeter.greeting())Method overriding does not imply inheriting every initializer. Swift initializer inheritance follows separate conditions, and a C callback constructor is simply a function.
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 C 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