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

Brent Royal-Gordon brent at architechies.com
Thu Apr 14 16:31:08 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’”.

You can't do `Key: String` because `String`, as a struct, cannot have any subtypes. `Key: NSString`, for instance, works.

What you really want to do is say `Key == String`, but this isn't supported right now. (My understanding is that this is basically just an implementation shortcut they took.)

One workaround is to define your own protocol and constrain to that:

	protocol _StringType: Hashable {
		// Include the String APIs you need to use here.
	}
	extension String: _StringType {}
	extension Dictionary where Key: _StringType { … }

-- 
Brent Royal-Gordon
Architechies



More information about the swift-users mailing list