7

Extending Classes

WHAT'S IN THIS CHAPTER?

  • Adding new methods and properties to existing classes
  • Ensuring that classes implement desired behavior using protocols
  • Adopting new protocols in existing classes
  • Composing protocols to create rich new data types
  • Creating generic functions that can work with many different data types

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

You can find the wrox.com downloads for this chapter at http://www.wrox.com/go/proswift on the Download Code tab. The code for this chapter is contained in the following files:

  • Colors.playground
  • Protocols.playground
  • Queue.playground
  • Squares.playground

Classes, structs, and enumerations are essential parts of Swift programming. Swift's type system ensures that types are always used in an expected, safe way, minimizing bugs in programs written in the language. While it may seem like this makes code inflexible and tedious to write, it turns out that Swift's type system is so powerful that the opposite is true: Using features of the language, you can easily write flexible code that still takes advantage of the safety offered by Swift.

WORKING WITH CLASS EXTENSIONS

One of the most visible features of Objective-C was categories. Categories allow Objective-C programmers to “open up” existing classes—including classes they don't control (or even have the source code for)—and to add new methods and properties to those classes. Objective-C's categories were originally conceived as a way to group related methods together in ...

Get Professional Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.