For fun, I am attempting to extend the Dictionary class to replicate Python's Counter class. I am trying to implement init
, taking a CollectionType
as the sole argument. However, Swift does not allow this because of CollectionType
's associated types. So, I am trying to write code like this:
import Foundation
// Must constrain extension with a protocol, not a class or struct
protocol SingletonIntProtocol { }
extension Int: SingletonIntProtocol { }
extension Dictionary where Value: SingletonIntProtocol { // i.e. Value == Int
init(from sequence: SequenceType where sequence.Generator.Element == Key) {
// Initialize
}
}
However, Swift does not allow this syntax in the parameter list. Is there a way to write init
so that it can take any type conforming to CollectionType
whose values are of type Key
(the name of the type used in the generic Dictionary<Key: Hashable, Value>
)? Preferably I would not be forced to write init(from sequence: [Key])
, so that I could take any CollectionType
(such as a CharacterView
, say).