gpt4 book ai didi

swift - 返回类型为 Self 而不是 Array 的 CollectionType 扩展

转载 作者:行者123 更新时间:2023-11-28 06:54:01 24 4
gpt4 key购买 nike

CollectionType 方法都是函数式的,返回集合的方法都返回数组。

是否可以创建一个通用函数来实现 map/forEach 之类的函数,但返回类型为 Self

extension CollectionType {

func otherMap(block: Generator.Element -> Generator.Element) -> Self {

var copy = self

copy.forEach {
$0 = block($0) // this obviously fails since $0 is immutable
}

return copy
}
}

更新:

这能统一吗?(我知道 func 名称说 mutate,即使它没有;))

extension Set {

func mutateCollection(block: Generator.Element -> Generator.Element) -> Set {

var copy : Set<Element> = []

for element in self {
copy.insert(block(element))
}

return copy
}
}

extension Dictionary {

func mutateCollection(block: Generator.Element -> Generator.Element) -> Dictionary {

var copy : [Key:Value] = [:]

for keyValuePair in self {

let key = keyValuePair.0
let value = keyValuePair.1

let blockResult = block(key, value)
copy[blockResult.0] = blockResult.1

}
return copy
}
}

extension Array {

func mutateCollection(block: Generator.Element -> Generator.Element) -> Array {

var copy : [Element] = []

for element in self {
copy.append(block(element))
}
return copy
}
}

最佳答案

不保证可以实例化或复制任意 CollectionType。所以没有办法实现你的扩展。了解这一点的一个好方法是尝试为 FlattenCollectionLazyCollection 实现它。或者尝试创建一个 RandomValueCollection,然后尝试实现此方法。

但是您可以在 RangeReplaceableCollectionType 上自由执行此操作,这会做出您需要的所有 promise :

extension RangeReplaceableCollectionType {
func otherMap(block: Generator.Element -> Generator.Element) -> Self {
var copy = Self.dynamicType.init()
self.forEach {
copy.append(block($0))
}
return copy
}
}

并非所有集合都符合 RangeReplaceableCollectionTypeSet 没有这样做可能是有充分理由的,因此您可能必须自己创建一个更简单的协议(protocol)。

请记住,CollectionType 可能代表一些没有意义或无法安全复制的静态内容。例如,我可能会制作一个 CollectionType 来表示“此磁盘上的文件”。复制它可能会使不变量无效(例如关于缓存和文件指针的假设)。无法保证 CollectionType 是值类型。免费作为引用。

关于swift - 返回类型为 Self 而不是 Array 的 CollectionType 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34181724/

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