我试图理解生成器和数列,这让我产生了实现斐波那契数列的想法。这很完美:
struct FibonacciGenerator : GeneratorType
{
typealias Element = Int
var current = 0, nextValue = 1
mutating func next() -> Int?
{
let ret = current
current = nextValue
nextValue = nextValue + ret
return ret
}
}
struct FibonacciSequence : SequenceType
{
typealias Generator = FibonacciGenerator
func generate() -> Generator
{
return FibonacciGenerator()
}
}
然后我决定使用 SequenceOf 和 GeneratorOf 来做同样的事情,但我坚持使用 GeneratorOf,它给我一个错误“找不到接受类型为‘(() -> _ 的参数列表的‘GeneratorOF’类型的初始化器)'"用于下一个代码。
var current = 0
var nextValue = 1
var fgOf = GeneratorOf{
let ret = current
current = nextValue
nextValue = nextValue + ret
return ret
}
但是如果我将它包装成一个函数,它就可以正常工作:
func getFibonacciGenerator() -> GeneratorOf<Int>
{
var current = 0
var nextValue = 1
return GeneratorOf{
let ret = current
current = nextValue
nextValue = nextValue + ret
return ret
}
}
为什么它的工作方式不同?这是一些 Xcode 错误还是我遗漏了什么?
最佳答案
GeneratorOf
的初始化器中使用的闭包具有以下类型
() -> T?
,并在
var fgOf = GeneratorOf {
let ret = current
current = nextValue
nextValue = nextValue + ret
return ret
}
编译器无法推断出 T
是什么。您可以制作区 block 签名
明确的
var fgOf = GeneratorOf { () -> Int? in
let ret = current
current = nextValue
nextValue = nextValue + ret
return ret
}
或者指定生成器的类型
var fgOf = GeneratorOf<Int> {
let ret = current
current = nextValue
nextValue = nextValue + ret
return ret
}
在你的最后一个例子中
func getFibonacciGenerator() -> GeneratorOf<Int>
{
// ...
return GeneratorOf {
// ...
return ret
}
}
之所以有效,是因为类型是从上下文中推断出来的(即
来自 getFibonacciGenerator()
的返回类型。
关于ios - GeneratorOf<T> 找不到初始化程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30828751/