Extended and protocol mixed use

1. Add protocol compliance in the extension

You can extend an existing type to adopt and conform to a new protocol, even if you don't have access to the source code of the existing type. Extensions can add new properties, methods, and subscripts to an existing type, and thus Allows you to add whatever the protocol requires.

protocol TextRepresentable {
    
    
    
    var textualDescription: String {
    
    get}
    
}
extension Dice: TextRepresentable
{
    
    
    var textualDescription: String {
    
    
        
        return "A \(sides)- sideed dice"
    }
    
}

2. Follow the protocol conditionally

A generic type may only meet the requirements of a protocol in certain circumstances, such as when the type's generic formal parameters conform to the corresponding protocol. You can make a generic type conditionally conform to a protocol by listing constraints when extending the type. Write the generic where clause after the name of the protocol you adopt.

extension Array: TextRepresentable where Element: TextRepresentable
{
    
    
    var textualDescription: String{
    
    
     
        let itemAsText = Self.map{
    
     $0.textualDescription}

        return "[" + itemAsText.joined(separator: ",") + "]"
        
    }
 
}

3. Use the extension declaration to adopt the protocol

If a type already conforms to all the requirements of the protocol, but has not declared that it adopts the protocol, you can make it adopt the protocol by passing an empty extension.

struct Hamster {
    
    
    
    var name: String
    var textualDescription:String {
    
    
        
        return "22"
    }
    
}
extension Hamster:TextRepresentable
{
    
    
    
    
}

4. Protocol extension

Protocols can be extended to provide method and property implementations for conforming types. This allows you to define behavior in the protocol itself, rather than per conformance or in a global function.

Guess you like

Origin blog.csdn.net/eastWind1101/article/details/124705476