0
0
Swiftprogramming~5 mins

Conditional conformance in Swift

Choose your learning style9 modes available
Introduction

Conditional conformance lets a type follow a protocol only if its parts also follow that protocol. This helps write flexible and reusable code.

When you want a generic type to conform to a protocol only if its generic parameters conform.
When you have a container type like an array or dictionary and want it to conform to a protocol only if the elements do.
When you want to add functionality to a type only under certain conditions.
When you want to avoid writing many versions of the same code for different types.
Syntax
Swift
extension TypeName: ProtocolName where GenericParameter: ProtocolName {
    // implementation
}
The where clause specifies the condition for conformance.
This feature helps keep code clean and avoids duplication.
Examples
This makes Array conform to Equatable only if its elements are Equatable.
Swift
extension Array: Equatable where Element: Equatable {
    static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool {
        guard lhs.count == rhs.count else { return false }
        for (l, r) in zip(lhs, rhs) {
            if l != r { return false }
        }
        return true
    }
}
Box conforms to CustomStringConvertible only if T does.
Swift
struct Box<T> {
    let value: T
}

extension Box: CustomStringConvertible where T: CustomStringConvertible {
    var description: String {
        "Box contains: \(value.description)"
    }
}
Sample Program

This program shows a generic Wrapper type that is Equatable only if its item is Equatable. We compare two wrappers with the same and different values.

Swift
struct Wrapper<T> {
    let item: T
}

extension Wrapper: Equatable where T: Equatable {
    static func ==(lhs: Wrapper<T>, rhs: Wrapper<T>) -> Bool {
        return lhs.item == rhs.item
    }
}

let a = Wrapper(item: 5)
let b = Wrapper(item: 5)
let c = Wrapper(item: 10)

print(a == b)  // true
print(a == c)  // false
OutputSuccess
Important Notes

Conditional conformance requires Swift 4.1 or later.

It helps avoid writing many versions of the same generic code.

Summary

Conditional conformance lets a type conform to a protocol only if its generic parts do.

Use where clauses to specify conditions.

This makes your code more flexible and reusable.