Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have protocol extension for a specific generics type in Swift?

Using protocol extensions, I can make any object conform to my own protocol as long as I provide an implementation for that. E.g. let's assume I create a protocol:

protocol Printable {
    // ... whatever ...
}

Now I can make Strings and Ints printable like that:

extension String: Printable {
    // ... whatever is required to satisfy protocol ...
}

extension Int: Printable {
    // ... whatever is required to satisfy protocol ...
}

This is a very cool way of programming as I now can feed Strings and Ints into whatever function I have that can deal with Printables.

Now if I have an Array of Printables, the whole Array is printable, so I try to do that:

extension Array<Printable>: Printable {
    // ... whatever is required to satisfy protocol ...
}

But the compiler doesn't like it.

Constraint extension must be declared on then unspecialized generic type "Array" with constraints specified by a "where" clause.

For normal extensions that isn't a problem. I can just do this:

extension Array where Element: Printable {

}

This works as expected. Whatever I put into the extension above only applies to Arrays of Printable elements. But this will not make an Array of Printable elements conform to the Printable protocol itself. This is just a normal extension, not a so called "protocol extension".

like image 434
Mecki Avatar asked Dec 02 '25 20:12

Mecki


1 Answers

You can do this in Swift 4.1

extension Array: Printable where Element: Printable {
    // ...
}
like image 173
Leonid Usov Avatar answered Dec 04 '25 11:12

Leonid Usov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!