๐Ÿ”ด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.

ๅ•๏ผš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

  • Declaring a method inside the protocol (definition) creates an extension point โ€“ a method that we encourage conforming types to override.

  • If we put methods into the protocol extension but not the protocol definition, all conforming types still get the method, except now weโ€™re making it harder for them to override. (๐Ÿ’ˆไพ‹ไบŒ)

  • define requirements for conforming types. (๐Ÿ’ˆไพ‹ไธ€)

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()    // true

Last updated