Search code examples
swiftgeneric-programming

Multiple constraints on parameter of a generic function


Reading about generic functions in Swift, I see that it is possible to put some constraints on a parameter by requiring, that it is a subclass of a given class C, or that it implements a given protocol P. But I wonder if there is a way to require both at the same time. I haven't found anything about that yet.

Does anyone know?


Solution

  • Actually You can do that.

    If you have seen Codable in swift it is actually Decodable and Encodable

     typealias Codable = Decodable & Encodable
    

    So in some function if you are using generic T as Codable

    struct StructOfCodable<T:Codable>: Codable {
         ....
    }
    

    Here is example

    protocol Test {}
    class TClass {
    
    }
    
    typealias Common = Test & TClass
    
    func generic <T:Common>(method:T) {
    
    }
    

    Another way is protocol and class both can have super class. So you can create common protocol

    like

    protocol CommonInProtocolAndStruct { }
    
    protocol ProtocolUsedAsConstraint:CommonInProtocolAndStruct {} 
    
    struct StructUsedAsConstraint:CommonInProtocolAndStruct {} 
    

    And any method you can use CommonInProtocolAndStruct as generic constraint