我尝试理解生成器和序列让我想到了实现Fibonacci序列的想法。这很完美:
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错误还是我错过了什么?
答案 0 :(得分:3)
GeneratorOf
的初始化程序中使用的闭包具有类型
() -> T?
,以及
var fgOf = GeneratorOf {
let ret = current
current = nextValue
nextValue = nextValue + ret
return ret
}
编译器无法推断T
是什么。您可以制作块签名
显式
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()
)的返回类型。