Learn what protocols are, and how to declare adoption of and conform to protocol requirements. See examples of conforming to common protocols in the Swift standard library.
- I'm starting out in a playground…that combines simplified versions of examples…I used previously in this chapter.…A protocol is essentially a contract defining requirements…that an adopting type agrees to implement…such as properties and methods.…You can define your own protocols,…but what I'm going to focus on here…is how to adopt and conform to existing protocols.…For example, I will make the ElectricVehicle class…adopt the CustomStringConvertible protocol…which requires implementing a description string property…so that the instance can be printed out…in a preferred format.…
An easy way to determine what a protocols requirements are…is by command clicking on it.…So now we'll implement the description property…required by this protocol.…This is a computed property,…meaning it does not store a value,…but instead calculates some returns of value,…a string in this case.…Computer properties are defined by writing curly braces…following the declaration,…and the type must be explicitly declared.…Now it can print an ElectricVehicle instance…
Learn how to write code, understand Swift's key concepts and best practices, and strengthen your programming problem-solving skills. Instructor Scott Gardner teaches the fundamentals, so you'll be prepared to develop applications for iOS, macOS, and other platforms. Completing this course will enable you to not only write first-class code, but to think like a Swift developer.
- Creating playgrounds
- Defining variables and constants
- Working with characters and strings
- Working with collections and groups
- Using operators and defining custom operators
- Controlling program flow
- Defining functions and closures
- Working with classes, structures, and enumerations
- Adopting protocols
Skill Level Beginner
1. Get Started
2. Variables and Constants
3. Characters and Strings
4. Collections and Tuples
6. Control Flow
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.