[Swift] About protocol extension

I use extensions when adding functionality to a type, Extensions can also be defined in protocols, which are called ** protocol extensions **.

Protocol extension is Instead of adding the interface required by the protocol ** It will add an implementation to the protocol. ** **

Definition method

Use the extension keyword to define a protocol extension.


extension protocol name{
Elements to implement in the target protocol
}

In the following sample code The Protocol protocol requires the name and value properties. Add an implementation there with an extension.

Features added in extensions do not need to be implemented in compliant types.


protocol Protocol {
    var name: String { get }
    var value: Int { get }
}

extension Protocol {
    var product: String {
        return "\(name)Is\(value)It is a circle."
    }
}

struct Sample: Protocol {
    var name: String
    var value: Int
}

let sample = Sample(name: "Pressure cooker", value: 7000)
print(sample.product)

Execution result
The pressure cooker costs 7,000 yen.

Optional implementation by default implementation

For the interface defined in the protocol If you add an implementation with a protocol extension, ** Implementation with a protocol-compliant type is optional. ** **

If the compliant type did not redefine the implementation This is called the ** default implementation ** because it uses the implementation of the protocol extension.

In the following sample code Protocol There are three properties for the protocol.

** Note property should be Optional \ type The output result changes depending on whether or not there is a value in this property. ** **

An extension is added to the Protocol protocol. In this case, we have added two default implementations.

** ① The getter of the note property returns nil. (2) Add the product property and change the output only when the note property is not nil. ** **

After that, define Book type and Kitchenware type Only the Kitchenware type has a value for the note property.

So the output of the two types will change.


protocol Protocol {
    var name: String { get }
    var value: Int { get }
    var note: String? { get }
}

extension Protocol {
    var note: String? {
        return nil
    }
    
    var product: String {
        var messages = "Product name:\(name)\n price:\(value)"
        if let note = note {
            //Executed when note is not nil
            messages += "\n Precautions:\(note)"
        }
        return messages
    }
}

struct Book: Protocol {
    var name: String
    var value: Int
    //note remains nil
}

struct Kitchenware: Protocol {
    var name: String
    var value: Int
    //A state with a value in note
    var note: String? {
        return "Please handle with care."
    }
}

let naruto = Book(name: "NARUTO", value: 600)
let knife = Kitchenware(name: "Kitchen knife", value: 3000)

print(naruto.product)
print("----")
print(knife.product)

Execution result
Product name:NARUTO
price:600
----
Product name:Kitchen knife
price:3000
Notes:Please handle with care.

By giving a default implementation in this way and making the implementation arbitrary, ** It can provide room for customization while providing standard functionality. ** **

This is the end of the explanation of the protocol extension.

Protocols define properties and methods that are common to different types, Furthermore, the relationship between these types is described by associative types.

By utilizing Putrocol, multiple types can be handled with a common interface, ** You can write more concise and extensible programs. ** **

So, if you can master the protocol, ** Increases code maintainability and readability. ** **

Let's get ready to use it!

-[Swift] Protocol concept and definition method -[Swift] Elements that make up the protocol

Thank you for watching until the end.

There are other articles about the protocol, so be sure to check them out.

Recommended Posts

[Swift] About protocol extension
[Swift] About generics
Swift extension collection
[Swift] About enumeration types
[Swift] Let's use extension
About [Cocoa] [Swift] AirPlay 2
[Swift] Protocol superiority over inheritance
[Swift] [Beginner]] About range operators
[Swift] Summary about Bool type
[Swift] About asynchronous processing "Operation"
[Swift] I thought about compare
[Swift] "for-in statement" about iterative processing
[Swift] Protocol concept and definition method
About =
[Java / Swift] Comparison of Java Interface and Swift Protocol
[Swift] Elements that make up the protocol