gpt4 book ai didi

swift - 如何在 Swift 中实例化 AnyGenerator

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:44 25 4
gpt4 key购买 nike

所以我尝试使用 AnyGenerator 来包装一个通用的 GeneratorType,但是我收到了错误:

Argument passed to call that takes no argument

这似乎是从一个奇怪的歧义延伸而来的,因为既有一个 AnyGenerator 结构(我期望的那个),也有一个 AnyGenerator 类作为实现的抽象类延长。

但是我不知道如何指定一个而不是另一个,因为我能找到的所有文档都建议我应该使用:

let someGenerator = ["foo"].generate()
let anyGenerator = AnyGenerator(someGenerator)

我还能做些什么吗?为了额外的乐趣,似乎还有一个 anyGenerator 全局函数,只是为了确保没有人知道发生了什么 ;)

最佳答案

您可以使用 anyGenerator<G : GeneratorType>(_: G) function创建你的 AnyGenerator<...>实例

signature:

func anyGenerator<G : GeneratorType>(base: G) -> AnyGenerator<G.Element>

description:

Return a GeneratorType instance that wraps base but whose type depends only on the type of G.Element.

例子:

struct Foo : GeneratorType {
typealias Element = String
mutating func next() -> String? {
return "foo"
}
}

var bar = anyGenerator(Foo())

func foofoo(bar: AnyGenerator<String>) {
print("foobar")
}

foofoo(bar) // "foobar", ok

正如我在对您的问题的评论中所写,您可能应该避免使用特定名称 anyGenerator特别是因为存在一个全局本地函数 anyGenerator(..) .


此外,请参阅@MartinR:对您上面的问题的评论;两个全局anyGenerator函数即将被弃用(Swift 2.2),并将在 Swift 3.0 中删除,以支持 AnyGenerator 上的初始化程序.

关于swift - 如何在 Swift 中实例化 AnyGenerator<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35604765/

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