๐ดProtocol Extensions
provide default implementations. (dynamic method dispatch) ๐ ๐ ๅ่
add new functionalities: (static method dispatch)
add methods
add (convenience) initializers (but not convenience override init)
add subscripts
add computed properties
make existing types conform to protocol.
cannot extend/inherit from another protocol. (protocol inheritance is always specified in the protocol definition. ๐ Swift โฉ Protocol Extensions)
cannot add stored properties.
cannot add property observers.
cannot add designated init or deinit to a class.
cannot override. (โ overriding declarations in extensions is not supported)
Swift โฉ
Nested Types in Extensions
ๅ๏ผprotocol extension ่ฃก้ขๅฏไปฅๅ nested types ๅ๏ผ
็ญ๏ผ็ฎๅ็ไพไธ่กโ๏ธ (๐ ๐ฃ ่จ่ซ)
Extensions can add new nested types to existing class, struct, and enum. (but not protocol extensionsโ) ๐Nested Types in Extensions
Protocol Definition vs. Protocol Extension
define requirements for conforming types. (๐ไพไธ)
provide default implementations for protocol requirements. (๐ไพไธ)
provide default values. (๐ไพไธ)
// ๐ธ protocol definition
protocol Logging {
func log(_ message: String) // method requirement
var filename: String { get } // property requirement
}
// ๐ protocol extension
extension Logging {
// โญ default implementation
func log(_ message: String) {
print("\(Date()): \(message).")
}
// โญ default value
var filename: String { return "app.log" }
}๐replit
// ๐ธ protocol definition
protocol Developer {}
// ๐ protocol extension
extension Developer {
// โญ added in extension but not in definition
func attendMeeting() { print("OK, let's go!") }
}
// ๐ฆ conforming type
struct SeniorDeveloper: Developer {
func attendMeeting() { print("No way!") }
}
// โญ protocol extension method is called
let dev: Developer = SeniorDeveloper()
dev.attendMeeting() // โญ "OK, let's go!"โ
// โญ instance method is called
let david = SeniorDeveloper()
david.attendMeeting() // โญ "No way!"Conditional Protocol Extensions
// โญโโโโโ condition โโโโโโโฎ
extension Collection where Element: Equatable {
func allEqual() -> Bool {
for element in self {
if element != self.first { return false }
}
return true
}
}
// test run
let numbers = [100, 100, 100, 100, 100]
numbers.allEqual() // trueSwift โฉ Protocol Extensions โฉ Adding Constraints to Protocol Extensions
Last updated
Was this helpful?