gpt4 book ai didi

swift - 在 Swift 中扩展 SequenceType

转载 作者:搜寻专家 更新时间:2023-11-01 06:43:10 24 4
gpt4 key购买 nike

我想知道为什么 SequenceType 中的 map()filter() 都返回一个 Array。其实我觉得没必要。再次返回一个序列对我来说感觉更明智。

但是,我在尝试添加顺序版本时遇到了困难。这是我对 map 的尝试:

extension SequenceType {

func seqMap<T, S: SequenceType where S.Generator.Element == T>(
transform: Self.Generator.Element -> T) -> S
{
var sourceGen = generate()
let tGen: AnyGenerator<T> = anyGenerator {
if let el = sourceGen.next() {
return transform(el)
} else {
return nil
}
}
return AnySequence { tGen }
}
}

XCode 在最后一个返回语句中告诉我以下错误:

cannot invoke initializer for type 'AnySequence<T>' with an argument list of type '(() -> AnyGenerator<T>)'
note: overloads for 'AnySequence<T>' exist with these partially matching parameter lists: (S), (() -> G)

实际上,我的tGen() -> G 类型,那么为什么XCode 认为它有歧义?

最佳答案

如果拆分 return 语句,问题会变得更加明显:

let tSeq = AnySequence { tGen }
return tSeq // error: cannot convert return expression of type 'AnySequence<T>' to return type 'S'

编译器会推断占位符类型 S从上下文一个方法调用,可以是任何序列类型与元素类型 T ,不一定是 AnySequence .

这是一个演示相同问题的简单示例:

protocol MyProtocol { }
struct MyType { }
extension MyType : MyProtocol { }

func foo<P : Protocol>() -> P {
return MyType() // error: cannot convert return expression of type 'MyType' to return type 'P'
}

要解决这个问题,将返回类型更改为AnySequence<T>并删除通用类型 S :

extension SequenceType {

func seqMap<T>(transform: Self.Generator.Element -> T) -> AnySequence<T>
{
var sourceGen = generate()
let tGen: AnyGenerator<T> = anyGenerator {
if let el = sourceGen.next() {
return transform(el)
} else {
return nil
}
}
return AnySequence { tGen }
}
}

可以更简洁地写成

extension SequenceType {

func seqMap<T>(transform: Self.Generator.Element -> T) -> AnySequence<T>
{
var sourceGen = generate()
return AnySequence(anyGenerator {
sourceGen.next().map(transform)
})
}
}

使用 map() Optional 的方法类型。

但请注意 SequenceType已经有一个 lazy返回的方法一个LazySequenceType :

/// A sequence containing the same elements as a `Base` sequence, but
/// on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceType`
public struct LazySequence<Base : SequenceType>

你可以使用

someSequence.lazy.map { ... }

获取映射值的(延迟评估的)序列。

关于swift - 在 Swift 中扩展 SequenceType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33581991/

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