Using AnyGenerator with Swift 2.2+ (quot;for inquot; loop support for custom classes)(在 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"循环支持)
基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01