[swift-users] Can't extend a generic type with a non-protocol constraint?

davelist at mac.com davelist at mac.com
Mon Apr 18 07:16:00 CDT 2016


> On Apr 14, 2016, at 4:58 PM, Jens Alfke via swift-users <swift-users at swift.org> wrote:
> 
> It appears that you can’t extend a generic class/struct with a requirement that a type parameter inherit from a non-protocol:
> 	extension Dictionary where Key : String { … }
> The above produces the error “Type ‘Key’ constrained to non-protocol type ‘String’”.
> 
> So is there a way I can add a method to a class, where the method depends on one of the type parameters being a specific type? For example, let’s say I want a “concatenatedKeys” method that returns all the Dictionary’s keys concatenated into a string with commas between them.
> 
> (The actual reason I’m doing this is more complicated, but it has to do with JSON encoding — JSON dictionary keys have to be strings, so I want to be type-safe and make my encoding methods available only for Dictionary<String, ___>.)
> 
> —Jens

I thought I replied last week but I don’t see it.

It looks like you can make it work using StringLiteralConvertible. Based on this:

http://stackoverflow.com/questions/32610150/extension-of-dictionary-where-string-anyobject

This works:

extension Dictionary where Key: StringLiteralConvertible, Value: Any {
    func testMethod() -> String {
        return "test"
    }
}

var d: [String: Int] = [:]
d["abc"] = 1
print(d.testMethod())

HTH,
Dave Reed



More information about the swift-users mailing list