Protocols and Conformance
Lesson 33 of 48 in Coddy's Swift for Rust Developers course.
Rust traits and Swift protocols declare behavior that types explicitly implement or conform to. A Rust dyn trait object enables dynamic dispatch subject to the trait's object-safety rules and reference lifetimes. Swift any Moving is an existential that can store values of conforming types; a generic constraint instead preserves a particular concrete type through an API. The source borrows two concrete values behind trait-object references, while the target array stores existential values. Both ask for behavior without testing concrete type names. Structs can implement these contracts as well as classes or other supported types, and ownership of the container remains a separate concern from the behavior interface.
Rust
trait Moving { fn movement(&self) -> &'static str; }
struct Bird;
struct Fish;
impl Moving for Bird { fn movement(&self) -> &'static str { "fly" } }
impl Moving for Fish { fn movement(&self) -> &'static str { "swim" } }
fn main() {
let bird = Bird;
let fish = Fish;
let animals: Vec<&dyn Moving> = vec![&bird, &fish];
println!("{}", animals.iter().map(|animal| animal.movement()).collect::<Vec<_>>().join(" "));
}
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
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 Rust 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