UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to use conditional conformance in Swift

Swift version: 5.6

Paul Hudson    @twostraws   

Conditional conformances were introduced in Swift 4.1, and refined in Swift 4.2 to allow you to query them at runtime. They allow types to conform to a protocol only when certain conditions are met – hence “conditional conformance”.

For example, if we had a Purchaseable protocol:

protocol Purchaseable {
    func buy()
}

And a simple type that conforms to that protocol:

struct Book: Purchaseable {
    func buy() {
        print("You bought a book")
    }
}

Then we could make Array conform to Purchaseable if all the elements inside the array were also Purchasable:

extension Array: Purchaseable where Element: Purchaseable {
    func buy() {
        for item in self {
            item.buy()
        }
    }
}

You can add conditional conformances to new types, and you can use any protocol you want – it doesn’t need to be one you define.

For example, you might a generic Box class that is able to wrap a value so it can be passed by reference:

final class Box<T> {
    var value: T

    init(value: T) {
        self.value = value
    }
}

We could use that box to store User structs, like this:

struct User: Equatable {
    var username: String
}

let user = User(username: "twostraws")
let box1 = Box(value: user)
let box2 = Box(value: user)

We’ve made the User struct Equatable, which means we can compare two instances of it to see if they are equal. What conditional conformance let us do is make Box equatable if its content is also equatable, like this:

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

With that in place, we can now check two boxes for equality directly, like this:

box1 == box2

Conditional conformance was enhanced in Swift 4.2, giving the ability to query a conditional conformance at runtime. Although this compiled in Swift 4.1, it would crash at runtime – a result no one wanted.

Well, that’s now fixed, so if you receive data of one type and want to check if it can be converted to a conditionally conformed protocol, it works great.

For example:

let items: Any = [Book(), Book(), Book()]

if let books = items as? Purchaseable {
    books.buy()
}
Hacking with Swift is sponsored by Proxyman

SPONSORED Proxyman: A high-performance, native macOS app for developers to easily capture, inspect, and manipulate HTTP/HTTPS traffic. The ultimate tool for debugging network traffic, supporting both iOS and Android simulators and physical devices.

Start for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 8.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.