Search code examples
swiftdictionarygenericsswift-protocolsswift-dictionary

Protocol Extension of Constrained Dictionary


I'm trying to get a specific Dictionary type to conform to a protocol.

typealias FirebaseDictionary = Dictionary<String, FirebaseValue>

I would like to have the conform to a FirebaseValue protocol

protocol FirebaseValue {
    // stuff here
}

I tried this

extension FirebaseDictionary: FirebaseValue {

}

but I got an error Constrained extension must be declared on the unspecialized generic type 'Dictionary' with constraints specified by a 'where' clause. So I now have this

extension Dictionary where Key == String, Value == FirebaseValue {

}

but I cannot figure out the proper syntax to make this conform to a protocol, if at all possible. If not possible is there any other way to achieve the same effect? I'm trying to only allow specific types into a property, and be able to discern easily what type they are when read back.

This question was asked but was given no definitive answer, and it may have changed regardless


Solution

  • Since Swift 4.2 you can do this with:

    extension Dictionary : FirebaseValue where Key == String, Value == FirebaseValue {
    }