Advanced Swift: Sequences, Collections and Algorithms · Sequences | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1940675-advanced-swift-sequences-collections-and-algorithms/lessons/2

Hello Ray!
Thank you for the “high quality” video series in advance :slight_smile:
AnySequence and AnyIterator are unfamiliar to me, so I need to study more.

I have a question for the last part of the video.
You use defer to make a pair sequence. I just wondering why you use defer.
In fact, I deleted defer and wrote the code like this to see what’s going on without defer:

return AnySequence {
  AnyIterator {
    if index1 >= self.endIndex || index2 >= self.endIndex { return nil }
    index2 = self.index(after: index2)
    if index2 >= self.endIndex {
      index1 = self.index(after: index1)
      index2 = self.index(after: index1)
    }

    return (self[index1], self[index2])
  }
}

All that I’ve done was delete defer ,unwrapped block and bring the contents to the front. But I got an error when I did that. I have no idea why I got this error if I don’t use defer. Can you explain what’s the difference using defer or not?

Sure. Thanks for the question. Defer lets you update a variable after you return it.

var number = 1
func returnAndIncrement() {
  defer {
    number += 1
  }
  return number
}

print(returnAndIncrement())
print(number)

This will print the value 1 then 2

If you leave the defer out the function is then increment and return. So it would print 2 then 2.

defer lets you implement a “generalized” post increment and post decrement found in C++ (index++ / index–) Instead of just letting you incrementing up and down though, you can perform any computation.

1 Like