Menu
CoddyTech

Inheritance and Overrides

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

Go has interfaces and embedding rather than class inheritance with virtual overrides. An embedded method may be promoted, but that is not a Swift superclass relationship. The source deliberately dispatches through a Greeter interface rather than claiming that one struct subclasses another.

Swift classes support one superclass and require override when replacing inherited behavior. Final prevents further subclassing or overriding at the chosen declaration. Swift structs instead use conformance and composition, and subclass initialization follows separate state-establishment rules.

Go: complete program

greeter.go

package main
type Greeter interface { Greeting() string }

formal.go

package main
type FormalGreeter struct{}
func (FormalGreeter) Greeting() string { return "Good day" }

main.go

package main
import (
    "fmt"
)

func main() {
var greeter Greeter = FormalGreeter{}
    fmt.Println(greeter.Greeting())
}

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())

The same greeting output demonstrates two different abstractions: Go interface dispatch and Swift class overriding. Do not assume Go embedding creates the same initializer or dynamic-self behavior as inheritance.

challenge icon

Challenge

Easy

Implement 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") }
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