ios - GeneratorOf<T> 找不到初始化程序错误

标签 ios swift xcode6

我试图理解生成器和数列,这让我产生了实现斐波那契数列的想法。这很完美:

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
}

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 错误还是我遗漏了什么?

最佳答案

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/

相关文章:

ios - xcode 6 beta 4 - MessageComposeResult 不可转换为 OptionalNilComparisonType

ios - swift curl ——用户帖子

ios - 查看已失效的 iPhone 应用程序的代码

ios - 如何使用 spritebuilder 创建简单的启动屏幕?

ios - 要发布或放置的 Alamofire 原始 json 字符串

swift - 如何在 swift 中将 UIImageView load() 函数与completionHandler一起使用

ios - LibGDX 使用 RoboVM 模拟 iOS 崩溃并出现架构不匹配错误

Ios 如何将谷歌地图用户数据传递到下一个 View

xcode - 如何将应用程序中本地通知的时间设置为两次之间随机? ( swift )

swift - 如何使用 Swift 在 playground 中获取用户交互事件