Reputation: 1252
I am currently learning Swift. While playing around with Generators I came across the following problem: Given a generator iter
. How do I go back one item?
For example:
var str = "Hello World"
var iter = str.characters.generate()
iter.next() // => H
...
iter.next() // => l
iter.next() // => o
// how can I get this functionality to go back?
iter.previous() => l
iter.next() => o
If not using generators: How can I get this behaviour to go forward and backward (in a String)?
Thanks in advance!
Upvotes: 1
Views: 129
Reputation: 4997
Use index:
var str = "Hello World"
let i0 = str.startIndex
let i1 = i0.successor()
let i00 = i1.predecessor()
str[i0] // H
str[i1] // e
str[i00] // H
Upvotes: 2