1

I'm stuck with this problem... I would like to enumerate in a regular for loop for one condition, and in reverse for another condition. Something like this:

var enumerator = 0..<length
if(stringPosition == .End) {
    enumerator = reverse(enumerator) //[C.Generator.Element] is not convertible to 'Range<Int>'
}
for index in enumerator {
    //do stuff
}

I'm getting a not convertible error there, and can't figure out how to proceed with that. I've tried different typecasting magic but that just doesn't work.

How should I sort out the conversion there?

Marko Hlebar
  • 1,973
  • 17
  • 18

1 Answers1

1

Just casting to Array should work.

var enumerator = Array(0..<length) // <-- here
if(stringPosition == .End) {
    enumerator = reverse(enumerator)
    // then, enumerator.reverse() is better, I think
}
for index in enumerator {
    //do stuff
}

I think, more (memory) efficient way is like:

let range = lazy(0..<length)
let enumerator = stringPosition == .End ? SequenceOf(range.reverse()) : SequenceOf(range)
for index in enumerator {
    //do stuff
}
  • SequenceOf is a wrapper of any SequenceType. You can use this to store different sequence type to one variable.
  • for lazy(), see this answer or this.
Community
  • 1
  • 1
rintaro
  • 51,423
  • 14
  • 131
  • 139