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

Jens Alfke jens at mooseyard.com
Thu Apr 14 15:58:39 CDT 2016


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160414/6ae06be3/attachment.html>


More information about the swift-users mailing list