Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional protocol conformance?

I want to do something like this:

class SomeClass<Element> { }
extension SomeClass: SomeProtocol where Element: String { }

It tells me:

Extension of type "SomeClass" with constraints cannot have an inheritance clause.

I could have sworn up to this point that this was one of the bread and butter features of the protocol/extension/generic/associatedtype paradigm. Is there another way to implement this?

like image 271
lanza Avatar asked May 21 '16 06:05

lanza


People also ask

What is conditional conformance?

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() }

What is protocol extension in Swift?

In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details, see Protocol Extensions. Note. Extensions can add new functionality to a type, but they can't override existing functionality.

Can Swift protocols have properties?

Protocols provide a blueprint for Methods, properties and other requirements functionality. It is just described as a methods or properties skeleton instead of implementation. Methods and properties implementation can further be done by defining classes, functions and enumerations.


1 Answers

This was implemented in Swift 4.1.

like image 78
lanza Avatar answered Oct 31 '22 04:10

lanza