Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access associated type of a custom protocol in a where clause on generic types in Swift

I would like to be able to declare a protocol like this :

protocol TypedHashable {

    typealias Type

}

and use it in a where clause like this :

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

For a reason I cannot see, the compiler gives me the following error under the dot of "K.Type" :

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

I've seen code using associated types declared using typealias in protocol accessing those typealias in where clause for type assertion. Here is some code that compiles and that do this using the Swift standard 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 from https://schani.wordpress.com/author/schani/)

The preceding code uses the Sequence declared associated type of the Sequence protocol which name is "GeneratorType".

Any idea?

like image 563
sebastienhamel Avatar asked Jul 17 '14 02:07

sebastienhamel


1 Answers

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

See "Metatype Type" from the Swift Programming Language:

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

You should probably get a compiler error on the typealias line rather than the class line, and you may want to open a radar on that.

like image 149
Rob Napier Avatar answered Nov 14 '22 04:11

Rob Napier