Chapter 3. Swift objects
This chapter covers
- Exploring objects, methods, and parameters in Swift
- Initializing properties
- Comparing inheritance with protocols
- Differentiating between classes and structs
- Exploring ways to extend your code
It’s impossible to do anything in iOS development without using objects. Views are objects, view controllers are objects, models are objects—even basic data types such as String, Int, and Array are objects in Swift!
An object in Swift is a specific instance of a type of thing. In this chapter, we’ll look at different ways of building up and structuring these types of things in your code. From experience in other languages, you may know this “type of thing” (or type) as a class. While it’s true that types can be represented by classes in Swift, they’re not the only type of thing in Swift—other types called structures and enumerations also exist. We’ll come back to those, but first let’s look at classes.
Don’t forget, you can refer to the Swift cheat sheets in appendix B. This chapter is summarized on the last page of the cheat sheets.
One approach for creating objects in Swift is with a class. A class defines what a type does with methods. A method is a function defined within a type. Along with methods, a class defines what a type is with properties. Properties are variables or constants stored in a type.