gpt4 book ai didi

swift - 了解 Swift map 定义中的 Self.Generator.Element 是什么

转载 作者:行者123 更新时间:2023-11-28 08:36:53 25 4
gpt4 key购买 nike

这里是 Swift 菜鸟。

许多函数在闭包定义的参数中都有 Self.Generator.Element。这到底是什么?我试图找到定义,但无处可去。

public func map<T>(@noescape transform: (Self.Generator.Element) throws -> T) rethrows -> [T]

最佳答案

这是一个已解析类型的通用协议(protocol)链。 Self是这个泛型协议(protocol)的采用者,它有一个关联类型叫Generator,Generator采用GeneratorType,它本身就是一个泛型协议(protocol),它有一个关联类型叫Element。所以 Self.Generator.Element 是 that 类型解析的任何内容。

这条链是序列(或集合)与其元素之间关系的基础。例如,如果 Self 是 CollectionType,则 Self.Generator.Element 是集合元素的类型。

因此,例如,一个字符串数组,类型 Array<String>[String] , 是一个集合,其 Self.Generator.Element 是字符串。所以 map方法的 transform函数(在您的示例中)会将字符串作为其参数。

(注意 map 没有说明 transform 函数输出的类型;它是一个纯通用占位符 T。编译器希望在编译时看到实际函数时能够解析 T .)

关于swift - 了解 Swift map 定义中的 Self.Generator.Element 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37491509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com