iOS, Objective-C, Swift, Design and Whatever Comes in Mind
‹ Back to the Blog

Swift 3: Conforming to Multiple Protocols

Have you ever tried to make a function that accepts a paramter that conforms to more than one protocol?
Or to declare a var that conforms to two protocols?

One way to accomplish this is

func duSomething4<T: protocolA>(argument: T) where T: protocolB {
}

I think that is not a good looking solution as you provide with additional type constraints after the method name and it gets split up.

The better way to do this is to use '&'. Using '&' you can chain protocol conformances together.

That being said, in a more convenient way you can write:

let aProperty: protocolA & protocolB = Something()
//and
func duSomething1<T: protocolA & protocolB>(argument: T) {
}

Here are other ways I tried, please note the spelling mistake 😅

"Swift 3: Conforming to Multiple Protocols".