Extensions
Protocol Conformance
An extension can make an existing type conform to a protocol.
Add conformance separately
protocol_conformance.swift
Replay: real traced execution (multi-file project)
protocol StatusLabel {
func statusLabel() -> String
}
struct Build {
let passed: Bool
}
extension Build: StatusLabel {
func statusLabel() -> String {
return passed ? "passed" : "failed"
}
}
let passed = true
let build = Build(passed: passed)
let label = build.statusLabel()
print(label)
protocol StatusLabel {
func statusLabel() -> String
}
struct Build {
let passed: Bool
}
extension Build: StatusLabel {
func statusLabel() -> String {
return passed ? "passed" : "failed"
}
}
let passed = false
let build = Build(passed: passed)
let label = build.statusLabel()
print(label)
passed ← true, build ← Build(passed: true)
15let passed→ true = true //@passed=false16let build→ Build(passed: true) = Build(passed: passedtrue)17let label = buildBuild(passed: true).statusLabel()func statusLabel() -> String
9extension Build: StatusLabel {10 func statusLabel() -> String {11 return passedtrue ? "passed" : "failed"12 }label ← passed
16let build = Build(passed: passed)17let label→ passed = buildBuild(passed: true).statusLabel()1819print(labelpassed)outputpassed
passed ← false, build ← Build(passed: false)
15let passed→ false = false16let build→ Build(passed: false) = Build(passed: passedfalse)17let label = buildBuild(passed: false).statusLabel()func statusLabel() -> String
9extension Build: StatusLabel {10 func statusLabel() -> String {11 return passedfalse ? "passed" : "failed"12 }label ← failed
16let build = Build(passed: passed)17let label→ failed = buildBuild(passed: false).statusLabel()1819print(labelfailed)outputfailed
extension conformance
Protocol conformance can be declared in an extension when the required members fit better outside the original type declaration.