Extending Your Own Type
You can also extend your own types. You might wonder why you would want to do that – if you created the type, why add an extension to it instead of editing the type itself? You will mostly use extensions on your own types for code organization. As you will see, extensions provide a convenient way to group related methods and behaviors, such as those required by a protocol.
You will need to create a new type before you can extend it.
Make a new struct to represent a Car
type and create an instance of it.
Car
struct... struct Car { let make: String let model: String let year: Int var fuelLevel: Double { willSet { precondition(newValue <= 1.0 && newValue >= 0.0, "New value must be between 0 and 1.") } } ...
Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition 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.