将AnyGenerator与Swift 2.2+结合使用(“& in"循环支持自定义类) [英] Using AnyGenerator with Swift 2.2+ ("for in" loop support for custom classes)

查看:50
本文介绍了将AnyGenerator与Swift 2.2+结合使用(“& 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:

但是在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]
    }
}

但是这会引发索引超出范围错误,因为我实际上需要使用预先递增的索引,然后在返回后将其递增.

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.

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

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())
}

这篇关于将AnyGenerator与Swift 2.2+结合使用(“&amp; in"循环支持自定义类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆