🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
使用Haxe,很容易定义定制的迭代器和可迭代数据类型。这些概念分别由类型 Iterator<T> 和 Iterable<T>为代表: > With Haxe it is very easy to define custom iterators and iterable data types. These concepts are represented by the types Iterator<T> and Iterable<T> respectively: ~~~ typedef Iterator<T> = { function hasNext() : Bool; function next() : T; } typedef Iterable<T> = { function iterator() : Iterator<T>; } ~~~ 任何在结构上和这些类型合一(第3.5.2节)的类都可以被通过使用 for循环迭代。也就是说,如果类定义了方法 hasNet 和 next包括匹配的返回类型,都可以被认为是一个迭代器,如果它定义了一个方法 iterator 返回一个 Iterator<T>,则被认为是可迭代类型。 > Any class (2.3) which structurally unifies (3.5.2) with one of these types can be iterated over usingafor-loop(5.13). Thatis,if the class defines methods hasNext and next with matching return types it is considered an iterator,if it defines a method iterator returning an Iterator<T> it is considered an iterable type. ~~~ class MyStringIterator { var s:String; var i:Int; public function new(s:String) { this.s = s; i = 0; } public function hasNext() { return i < s.length; } public function next() { return s.charAt(i++); } } class Main { static public function main() { var myIt = new MyStringIterator("string"); for (chr in myIt) { trace(chr); } } } ~~~ 本例中的类型 MyStringIterator 有资格作为迭代器:它定义了一个方法 hasNext,返回Bool,和一个方法 next,返回String,使它兼容于 Iterator<String>。main方法实例化了它,然后进行迭代。 > The type MyStringIterator in this example qualifies as iterator: It defines a method hasNext returning Bool and a method next returning String, making it compatible with Iterator<String>. The main method instantiates it, then iterates over it. ~~~ class MyArrayWrap<T> { var a:Array<T>; public function new(a:Array<T>) { this.a = a; } public function iterator() { return a.iterator(); } } class Main { static public function main() { var myWrap = new MyArrayWrap([1, 2, 3]); for (elt in myWrap) { trace(elt); } } } ~~~ 这里我们没有设置一个像上利中完整的迭代器,而是定义MyArrayWrap<T> 有一个方法 iterator ,有效的转发包装的Array<T>类型的iterator方法。 > Here we do not setup a full iterator like in the previous example, but instead define that the MyArrayWrap<T> has a method iterator, effectively forwarding the iterator method of the wrapped Array<T> type.