Protocols and Conformance
Lesson 33 of 48 in Coddy's Swift for Lua Developers course.
Lua table-based objects can supply methods without declaring a shared interface. announce calls greeting through the supplied table, and a missing or incompatible method fails when that path executes. The colon call also passes the receiver, so a port must preserve the method's parameter convention.
A Swift protocol declares required properties or methods. A type explicitly declares conformance and supplies compatible implementations. A generic constraint lets a function call those guaranteed members without inspecting a concrete type name. A readable stored property can satisfy a get-only requirement.
Both announce functions ask their provider for a greeting. Swift checks the contract at compilation, while this Lua program relies on its runtime table shape. Implement the task's required rating behavior through its protocol rather than branching on particular conforming types.
Complete Lua comparison program:
local Host = {}
function Host:greeting() return "welcome" end
local function announce(provider) return provider:greeting() end
print(announce(Host))
Complete Swift comparison program, compiled from these files:
Greeting.swift
protocol Greeting { func greeting() -> String }Host.swift
struct Host: Greeting { func greeting() -> String { "welcome" } }Functions.swift
func announce<T: Greeting>(_ provider: T) -> String { provider.greeting() }main.swift
print(announce(Host()))Challenge
EasyImplement protocol Rated requiring rating: Int { get }. Implement Review: Rated with stored rating and init(rating:). Implement generic totalRating<T: Rated>(_ items: [T]) -> Int in Functions.swift to sum every rating, including those of other conforming types. Input has 0 through 50 ratings 0 through 5; output the sum.
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 Rated.swift, Review.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 {
struct ProbeRated: Rated { let rating: Int }
let custom = ProbeRated(rating: 4); return totalRating([custom, ProbeRated(rating: 2)]) == 6 && totalRating([Review(rating: 3)]) == 3 && totalRating([Review]()) == 0
}
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 Steps7Failures and Abstraction
Throwing Functions and CatchResult as a Stored OutcomeProtocols and ConformanceExtensions Add BehaviorGeneric Value ContainersRecap: Validated Batch2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground