Menu
CoddyTech

Protocols and Conformance

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

Python duck typing allows a function to call a method without requiring a declared common base class. Missing behavior may fail at runtime. Python typing protocols can describe structural requirements to static tools, but those hints do not turn ordinary execution into Swift’s compile-time conformance checking.

A Swift protocol declares required properties or methods. Types explicitly conform and supply compatible implementations. A get-only property requirement can be satisfied by a readable stored property. A generic constraint lets a function use those guaranteed members without knowing a concrete type.

The example requests a greeting from different possible providers. The task uses a readable rating requirement instead. Focus on the required API, not on detecting a particular conforming type.

Complete Python comparison program:

class Host:
    def greeting(self):
        return "welcome"
def announce(provider):
    return provider.greeting()
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 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 Python Developers

Practice on your own: Swift playground