Menu
CoddyTech

Protocols and Conformance

Lesson 33 of 48 in Coddy's Swift for C++ Developers course.

C++ abstract base classes can specify virtual behavior and dispatch through references or pointers. Templates offer a different compile-time abstraction, and neither mechanism is identical to a Swift protocol. Swift structs, enums and classes may explicitly conform to protocols with methods, initializers or readable properties. A get-only requirement does not require immutable stored data; a mutable property or computed getter may satisfy it. The source uses an abstract reference while the target stores any Greeting as an existential value. Generic protocol constraints instead retain a particular conforming type per instantiation. Keep the behavior requirement independent of concrete storage.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
struct Greeting { virtual std::string text() const = 0; virtual ~Greeting() = default; };
struct Salutation : Greeting { std::string text() const override { return "welcome"; } };

int main() {
Salutation value;
    const Greeting &greeting = value;
    std::cout << greeting.text() << '\n';
}

Swift

Complete program file: Greeting.swift.

protocol Greeting { var text: String { get } }

Complete program file: Salutation.swift.

struct Salutation: Greeting { var text = "welcome" }

Complete program file: main.swift.

let greeting: any Greeting = Salutation()
print(greeting.text)
challenge icon

Challenge

Easy

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

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for C++ Developers

Practice on your own: Swift playground