Chapter 9. Iterators, sequences, and collections

 

This chapter covers

  • Taking a closer look at iteration in Swift
  • Showing how Sequence is related to IteratorProtocol
  • Learning useful methods that Sequence supplies
  • Understanding the different collection protocols
  • Creating data structures with the Sequence and Collection protocols.

You use iterators, sequences, and collections all the time when programming Swift. Whenever you use an Array, String, stride, Dictionary, and other types, you’re working with something you can iterate over. Iterators enable the use of for loops. They also enable a large number of methods, including, but not limited to, filter, map, sorted, and reduce.

In this chapter, you’re going to see how these iterators work, learn about useful methods (such as reduce and lazy), and see how to create types that conform to the Sequence protocol. The chapter also covers the Collection protocol and its many subprotocols, such as MutableCollection, RandomAccessCollection, and others. You’ll find out how to implement the Collection protocol to get a lot of free methods on your types. Being comfortable with Sequence and Collection will give you a deeper understanding of how iteration works, and how to create custom types powered up by iterators.

You’ll start at the bottom and build up from there. You’ll get a look at how for loops work and how they are syntactic sugar for methods on IteratorProtocol and Sequence.

9.1. Iterating

9.2. The powers of Sequence

9.3. Creating a generic data structure with Sequence

9.4. The Collection protocol

9.5. Creating a collection

9.6. Closing thoughts

Summary

Answers

sitemap