GeneratorOf <t>找不到初始化程序错误

时间:2015-06-14 11:20:54

标签: ios swift xcode6

我尝试理解生成器和序列让我想到了实现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,这给了我一个错误&#34;找不到类型&#39; GeneratorOF&#39;接受类型&#39;(() - &gt; _)&#39;&#34;的参数列表;下一个代码。

var current = 0
var nextValue = 1

var fgOf = GeneratorOf{
    let ret = current
        current = nextValue
        nextValue = nextValue + ret
        return ret
}

enter image description here

但是如果我把它包装成一个函数它可以正常工作:

    func getFibonacciGenerator() -> GeneratorOf<Int>
{

    var current = 0
    var nextValue = 1

    return GeneratorOf{
        let ret = current
        current = nextValue
        nextValue = nextValue + ret
        return ret
    }
}

为什么它的工作方式不同?这是一些Xcode错误还是我错过了什么?

1 个答案:

答案 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())的返回类型。