在 Swift 2.2+ 中使用 AnyGenerator(自定义类的“for in"循环支持)

Using AnyGenerator with Swift 2.2+ (quot;for inquot; loop support for custom classes)(在 Swift 2.2+ 中使用 AnyGenerator(自定义类的“for in循环支持))

本文介绍了在 Swift 2.2+ 中使用 AnyGenerator(自定义类的“for in"循环支持)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前我使用以下函数使我的自定义类符合 SequenceType 协议:

Previously I was using the following function to make my custom class conform to the SequenceType protocol:

func generate() -> AnyGenerator<UInt32> {

    var nextIndex = 0

    return anyGenerator {
        if (nextIndex > self.scalarArray.count-1) {
            return nil
        }
        return self.scalarArray[nextIndex++]
    }
}

这是与这两个问题的公认答案类似的实现:

This is a similar implementation to the accepted answers to these two questions:

  • 添加for in"支持迭代 Swift 自定义类
  • 添加for...in"支持到 Swift 2 中的一个类

但是在 Swift 2.2 更新之后...

'++' 已弃用:它将在 Swift 3 中删除

'++' is deprecated: it will be removed in Swift 3

func generate() -> AnyGenerator<UInt32> {

    var nextIndex = 0

    return AnyGenerator {
        if (nextIndex > self.scalarArray.count-1) {
            return nil
        }
        nextIndex += 1
        return self.scalarArray[nextIndex]
    }
}

但这会引发 Index out of range 错误,因为我实际上需要使用预先递增的索引,然后在返回后递增它.

But this throws an Index out of range error because I actually need to use the pre-incremented index and then increment it after the return.

AnyGenerator 现在在 Swift 中如何工作?(另外,我应该像我链接的其他两个答案那样递减而不是递增吗?)

How does this work for AnyGenerator now in Swift? (Also, should I be decrementing rather than incrementing as the other two answers I linked to do?)

推荐答案

(我假设你的代码是指struct ScalarString来自 在 Swift 中使用 Unicode 码位.)

(I assume that your code refers to struct ScalarString from Working with Unicode code points in Swift.)

您可以在确定后执行 Swift 2.2+ 兼容的增量索引"defer 的返回值":

You can do a Swift 2.2+ compatible "increment index after determining the return value" with defer:

func generate() -> AnyGenerator<UInt32> {

    var nextIndex = 0

    return AnyGenerator {
        if nextIndex >= self.scalarArray.count {
            return nil
        }
        defer {
            nextIndex += 1
        }
        return self.scalarArray[nextIndex]
    }
}

但是,在您的特殊情况下,只需转发生成器

In your special case however, it would be easier to just forward the generator of the

private var scalarArray: [UInt32] = []

属性,或者直接:

func generate() -> IndexingGenerator<[UInt32]> {
    return scalarArray.generate()
}

或者作为一个类型擦除的生成器转发 next() 方法到数组生成器:

or as a type-erased generator which forwards the next() method to the array generator:

func generate() -> AnyGenerator<UInt32> {
    return AnyGenerator(scalarArray.generate())
}

这篇关于在 Swift 2.2+ 中使用 AnyGenerator(自定义类的“for in"循环支持)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Swift 2.2+ 中使用 AnyGenerator(自定义类的“for in"循环支持)

基础教程推荐