Protocols and Conformance
Lesson 33 of 48 in Coddy's Swift for Go Developers course.
Go interface satisfaction is implicit when a type method set supplies the required methods. Swift protocols require declared conformance and compatible implementations. A Swift readable property requirement does not require a specific storage representation or an immutable field.
The source Panel method satisfies Titled without an implements declaration. The target Panel struct explicitly conforms and exposes a stored title property. Go pointer and value method sets can differ, while Swift generic constraints let a function call the guaranteed protocol requirement.
Go: complete program
titled.go
package main
type Titled interface { Title() string }
panel.go
package main
type Panel struct { TitleText string }
func (panel Panel) Title() string { return panel.TitleText }
main.go
package main
import (
"fmt"
)
func main() {
var item Titled = Panel{TitleText: "settings"}
fmt.Println(item.Title())
}
Swift: complete program
Titled.swift
import Foundation
protocol Titled { var title: String { get } }Panel.swift
import Foundation
struct Panel: Titled { let title: String }Functions.swift
import Foundation
func show<T: Titled>(_ item: T) -> String { item.title }main.swift
import Foundation
print(show(Panel(title: "settings")))A computed getter or mutable stored property may satisfy a Swift get-only requirement. Separate the available behavior from whether its underlying storage can change.
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 Go 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