0
0
Swiftprogramming~5 mins

Protocol conformance via extension in Swift

Choose your learning style9 modes available
Introduction

Protocol conformance via extension lets you add behavior to a type without changing its original code. It helps keep your code organized and flexible.

When you want to add new features to a type after it is defined.
When you want to separate protocol requirements from the main type code.
When you want to make an existing type conform to a protocol without editing its source.
When you want to share common behavior across many types using protocols.
When you want to keep your code clean by grouping protocol methods together.
Syntax
Swift
extension TypeName: ProtocolName {
    // implement protocol requirements here
}

You write extension followed by the type name and the protocol name.

Inside the braces, you add the methods or properties the protocol needs.

Examples
This example makes Person conform to Greetable by adding greet() in an extension.
Swift
protocol Greetable {
    func greet()
}

struct Person {
    let name: String
}

extension Person: Greetable {
    func greet() {
        print("Hello, \(name)!")
    }
}
This example adds Describable conformance to Int by providing a computed property description.
Swift
protocol Describable {
    var description: String { get }
}

extension Int: Describable {
    var description: String {
        return "Number \(self)"
    }
}
Sample Program

This program defines a Printable protocol and makes Book conform to it using an extension. Then it prints the book details.

Swift
protocol Printable {
    func printDetails()
}

struct Book {
    let title: String
    let author: String
}

extension Book: Printable {
    func printDetails() {
        print("Book: \(title) by \(author)")
    }
}

let myBook = Book(title: "Swift Basics", author: "Jane Doe")
myBook.printDetails()
OutputSuccess
Important Notes

Extensions can add protocol conformance even to types you do not own, like standard library types.

If the protocol has required initializers, you cannot add them in extensions.

Using extensions helps keep your main type code clean and focused.

Summary

Use extensions to make types conform to protocols without changing original code.

This keeps code organized and allows adding features later.

Extensions can add methods and properties required by protocols.