Protocols
Protocol Parameters
Functions can accept any value that conforms to a protocol.
Pass conforming values
protocol_parameters.swift
protocol PrintableStatus {
func statusText() -> String
}
struct Job: PrintableStatus {
let name: String
let finished: Bool
func statusText() -> String {
return finished ? "\(name):done" : "\(name):open"
}
}
func renderStatus(_ item: PrintableStatus) -> String {
return item.statusText()
}
let finished =
let job = Job(name: "build", finished: finished)
let output = renderStatus(job)
print(output)
protocol PrintableStatus {
func statusText() -> String
}
struct Job: PrintableStatus {
let name: String
let finished: Bool
func statusText() -> String {
return finished ? "\(name):done" : "\(name):open"
}
}
func renderStatus(_ item: PrintableStatus) -> String {
return item.statusText()
}
let finished =
let job = Job(name: "build", finished: finished)
let output = renderStatus(job)
print(output)
protocol type
A protocol parameter lets a function depend on required behavior instead of a specific concrete type.