Home » Swift » generic type conforming to a protocol in Swift

generic type conforming to a protocol in Swift

Posted by: admin November 30, 2017 Leave a comment


Is it possible to require that specific instantiations of generic types conform to a protocol in Swift?

For example, say I have a generic type called Thing<T>. I want Thing<Int> to conform to a certain protocol, but not Thing<T>.


Well, it might not be too onerous, and it might be obvious enough that you’ve ignored it, but you could make a ‘specific instantiation of a generic type’ – as:

class ThingOfInt : Thing<Int>, SpecialIntProtocol {
 // implement SpecialIntProtocol (if it isn't already 
 // implemented in an extension)

or with a bit more generality:

class IntThing<T:IntegerType> : MyThing<T>, SpecialIntProtocol {


In Swift 2.0 you can extend protocols and types

When you extend it you can add a generic where constraints. Only types that matches that rule will be able to use that functionality


public struct Thing<T> {
  let x: T

extension Thing where T : IntegerType {
  func giveMeInt () -> T {
    return x

let a = Thing<Int>(x: 10)

let b = Thing(x: 10.1)
//b.giveMeInt() // Error

This way you can add an extra functionality to Thing<Int> type

I don’t know a way to conform to a protocol in the extension, but it doesn’t make much sense.

Limitation: Generic where T : can be used with protocols and classes, that’s why we can’t specify Int there


You can do something like using the where keyword and pass a condition afterwords. Saw this under Where Clauses section https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html#//apple_ref/doc/uid/TP40014097-CH26-XID_275

class Thing<T : SomeProtocol where reflect(T).summary != "Int"> {