Swift Introduction | Protocols and Extensions | Combining Protocols and Extensions

Combining protocols and extensions enables useful designs.

An extension can add a protocol as well as methods and properties. This lets multiple existing types implement common behavior and be processed together.

protocol MyDataPrintable {
    func printData ()
}

extension String: MyDataPrintable {
    func printData() {
        print("문자열 : \(self).")
    }
}

extension Int: MyDataPrintable {
    func printData() {
        print("숫자 : \(self).")
    }
}

var str = "Hello"
var num = 12345
str.printData()
num.printData()

This example declares the MyDataPrintable protocol with a printData method. Extensions then add protocol conformance to String and Int.

extension String: MyDataPrintable {...}
extension Int: MyDataPrintable {...}

Every String and Int value can now be treated as MyDataPrintable. You can process both types uniformly through the same protocol.

Protocols and extensions do more than improve your own classes. They also let you customize types included with Swift.