lanza
lanza

Reputation: 1632

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?

Upvotes: 7

Views: 1426

Answers (2)

lanza
lanza

Reputation: 1632

This was implemented in Swift 4.1.

Upvotes: 1

rahulg
rahulg

Reputation: 2249

As Paul, you can now do it in Swift 4

protocol Nameable {
    var name:String {get set}
}
func createdFormattedName<T:Nameable>(_ namedEntity:T) -> String where T:Equatable {
    //Only entities that conform to Nameable which also conform to equatable can call this function
    return "This things name is " + namedEntity.name
}

Upvotes: 0

Related Questions