Accessing the associated custom protocol type in the where clause for generic types in Swift

I would like to declare a protocol as follows:

protocol TypedHashable { typealias Type } 

and use it in the where clause as follows:

 class UsingTypedHashable<K: TypedHashable, V: TypedHashable where K.Type == V.Type> { ... } 

For some reason, I don’t see the compiler giving me the following error under the point β€œK.Type”:

Expected ':' or '==' to indicate a conformance requirement or the same type

I saw code using related types declared with typealias in a protocol that accesses these typealias in where where for type statements. Here is some code that compiles and executes this using the standard Swift protocol: "Sequence (and generator ...):

 func toArray<S : Sequence, T where T == S.GeneratorType.Element> (seq : S) -> T[] { var arr = T[]() for x in seq { arr.append(x) } return arr } 

(Note: code https://schani.wordpress.com/author/schani/ )

The previous code uses the sequence protocol type associated with Sequence, whose name is "GeneratorType".

Any idea?

+6
source share
1 answer

The problem is that you are using the reserved word Type . Try it with some other name, like HashType , and it compiles fine.

See "Metatype Type" in Swift:

A metatype of a type, structure, or enumeration is the name of that type, followed by .Type .

You should probably get a compiler error in the typealias line, not the class line, and you might need to open the radar.

+2
source

Source: https://habr.com/ru/post/972360/


All Articles