O'Reilly logo

Professional Swift by Michael Dippery

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required