在Swift中的泛型类型的where子句中访问自定义协议的关联类型

时间:2023-01-23 23:44:32

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 :

并在像这样的where子句中使用它:

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" :

由于我无法看到的原因,编译器在“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...) :

我已经看到使用协议中使用typealias声明的关联类型的代码访问类型断言的where子句中的那些typealias。下面是一些使用Swift标准协议Sequence(和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/)

(注意:来自https://schani.wordpress.com/author/schani/的代码)

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

前面的代码使用序列协议的Sequence声明的关联类型,其名称为“GeneratorType”。

Any idea?

1 个解决方案

#1


2  

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

问题是你正在使用保留字Type。尝试使用其他名称,如HashType,它编译得很好。

See "Metatype Type" from the Swift Programming Language:

请参阅Swift编程语言中的“元类型类型”:

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

类,结构或枚举类型的元类型是该类型的名称,后跟.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.

您应该在typealias行而不是类行上获得编译器错误,并且您可能想要打开雷达。

#1


2  

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

问题是你正在使用保留字Type。尝试使用其他名称,如HashType,它编译得很好。

See "Metatype Type" from the Swift Programming Language:

请参阅Swift编程语言中的“元类型类型”:

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

类,结构或枚举类型的元类型是该类型的名称,后跟.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.

您应该在typealias行而不是类行上获得编译器错误,并且您可能想要打开雷达。