Menu
CoddyTech

Protocols and Conformance

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

Kotlin interfaces and Swift protocols describe requirements that multiple types can satisfy. Swift protocols can be adopted by structs, enums, and classes, so an abstraction does not force reference semantics. A property requirement states whether callers need read-only or read-write access; a getter-only requirement can be satisfied by a stored let property. A generic function constrained to a protocol uses the required API without depending on a particular concrete type. Swift also uses any to spell an existential value that can hold different conforming types. The example asks several types for a description of how they move, keeping movement behavior behind a shared requirement.

Kotlin

interface Moving { fun move(): String }
class Bird : Moving { override fun move() = "fly" }
class Fish : Moving { override fun move() = "swim" }
fun main() {
    val animals: List<Moving> = listOf(Bird(), Fish())
    println(animals.joinToString(" ") { it.move() })
}

Swift

protocol Moving { func move() -> String }
struct Bird: Moving { func move() -> String { "fly" } }
struct Fish: Moving { func move() -> String { "swim" } }
let animals: [any Moving] = [Bird(), Fish()]
print(animals.map { $0.move() }.joined(separator: " "))
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 Kotlin Developers

Practice on your own: Swift playground