How to define an extension for CollectionType so that its methods are accessible for dictionaries?

I recently managed to change the extension from:

extension Array where Element: Encodable { ... } 

in

 extension CollectionType where Generator.Element: Encodable { ... } 

so that later you can apply type restrictions with CollectionType and Encodable in another extension.

Now I'm trying to do the same with Dictionary , changing:

 extension Dictionary where Key: StringLiteralConvertible, Value: Encodable { ... } 

in

 extension CollectionType where Generator.Element == (Key: StringLiteralConvertible, Value: Encodable) { ... } 

However, the latter does not seem to be a valid replacement for the Dictionary type, since now the methods defined in the extension cannot be called in dictionaries.

How to define an extension for CollectionType (or possibly SequenceType ) so that its methods are accessible for dictionaries?


Update

I wanted to notice that I tried to add type constraints as follows, without success:

 extension CollectionType where Self: protocol<Indexable, SequenceType, DictionaryLiteralConvertible>, Self.Key: protocol<Hashable, StringLiteralConvertible>, Self.Value: Encodable, Self.Generator.Element == (Key: StringLiteralConvertible, Value: Encodable) { ... } 

Update 2

Since user2194039 asked, I would rather not do this and save the extensions to Array and Dictionary .

However, I also need to write extensions for Optional options. I understand that due to the use of generics, it is not possible to write a type constraint for Optional that restricts it to Array or Dictionary .

+5
source share
2 answers

This works for my current use case:

 extension CollectionType where Self: DictionaryLiteralConvertible, Self.Key: StringLiteralConvertible, Self.Value: Encodable, Generator.Element == (Self.Key, Self.Value) { ... } 
+2
source

Thanks for posting your solution, it helped a lot, I converted your solution to swift 3, but I don’t know why it doesn’t work for me, so I want to publish my solution, maybe it can help someone else.

 extension Collection where Self: ExpressibleByDictionaryLiteral, Self.Key: ExpressibleByStringLiteral, Self.Value: ExpressibleByStringLiteral, Iterator.Element == (key: Self.Key, value: Self.Value) { ... } 

I could also bind a collection to a specific type:

 extension Collection where Self: ExpressibleByDictionaryLiteral, Self.Key == String, Self.Value == Array<String>, Iterator.Element == (key: Self.Key, value: Self.Value) 

The key was Iterator.Element == (key: Self.Key, value: Self.Value)

thanks for the help

+1
source

All Articles