Java-like Iterator in Swift -
how iterate array without using position (index) i , for/for in loop?
var = [1, 2, 3] var = 0; < a.count; i++ { // } item in { // }
a sequencetype (which collectiontype, , swift collections including array, conform to) pretty simple. requires provide generate() function returns type conforming generatortype.
generatortype in turn needs provide 1 method: next() returns each element until elements exhausted. returns optional, returning nil after last element returned. makes them pretty similar java iterators, next , hasnext combined 1 via use of optionals.
swift’s for…in syntactic sugar combination of getting generator , repeatedly calling next on it:
let = [1, 2, 3] in { print(i) } // equivalent to: var g = a.generate() // generator, being stateful, must declared var while let = g.next() { print(i) } if using generators this, take note of comment above definition of generatortype in std lib doc:
encapsulates iteration state , interface iteration on sequence.
- note: while safe copy generator, advancing 1 copy may invalidate others.
since writing generator collection involves lot of boiler plate, there helper type, indexinggenerator, can used. implements generator starts @ startindex, , returns value @ index , increments index each time. generate() returns indexinggenerator provided default implementation collectiontype, means if enough purposes, don’t need implement generate when implementing collection:
struct bitfield: collectiontype { let data: uint var startindex: uint { return 0 } var endindex: uint { return uint(sizeofvalue(data)*8) } subscript(idx: uint) -> bit { return (data >> idx) & 1 == 0 ? bit.zero : bit.one } // no need implement generate() } this default added in swift 2.0. prior that, had provide minimal generator returned indexinggenerator(self).
Comments
Post a Comment