Search code examples
swiftgenericsnsmutabledictionaryswift-dictionary

How to declare protocol constrainted generic variable in Swift?


I need to create a dictionary variable where my value will be of SomeOtherClass class and conforms to SomeProtocol. This equals to the following declaration in Objective-C:

NSMutableDictionary<SomeClass *, SomeOtherClass<SomeProtocol> *> *someOtherBySome;

So, is it possible to do it in the same simple way using Swift?

I need it because I can create func with signature:

func someFunc<T: SomeOtherClass where T: SomeProtocol>(param: T, otherParam: String)

and I want to get values for param parameter from Dictionary without type casting.


Solution

  • Short answer

    In Swift you cannot declare a variable of a given class and conform to a protocol.

    Possible solution (?)

    However given the definitions you already have

    class SomeClass: Hashable {
        var hashValue: Int { return 0 } // your logic goes here
    }
    
    func ==(left:SomeClass, right:SomeClass) -> Bool {
        return true // your logic goes here
    }
    
    class SomeOtherClass {}
    protocol SomeProtocol {}
    

    maybe you can solve your problem simply making SomeOtherClass conform to SomeProtocol

    extension SomeOtherClass: SomeProtocol { }
    

    Now you can simply

    var dict : [SomeClass: SomeOtherClass] = [SomeClass(): SomeOtherClass()]
    
    let someProtocolValue: SomeProtocol = dict.values.first!
    

    Does it help you?