Swift version: 5.10
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()
}
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.