Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Tobias Schmidt
1,526 PointsWhat are Swift Protocols for?
Helle All,
can someone explain me in simple Englisch what Protocols are, when to use them and why they are used so frequent in Swift.
Thank you, Tobias
3 Answers
JP Dela Torre
3,390 PointsAnother way to look at it is that Protocol is a way of organizing your code. You can think of it like a template/blueprint for your classes. It gives sort of a structure to your code.
Take for example a class Airplane. You can have a protocol Fly with methods like takeOff and land. Of course you can just do the takeOff and land method on your airplane without using the Fly protocol but what if you're also creating a class Helicopter, Spaceship or a Bird. Protocol provides structure to your classes. You'll know that any object that is using Fly protocol will have a methods takeOff and land.
You see a lot of protocols being used because it's part of some framework. One of the goals of a framework is to make code reusable and that's how Protocol fits in.
Hope this makes sense.
Leo Picado
9,182 PointsProtocols define behavior and allow a class to do more than what it was intended to do, say for instance if you have a regular view, then implement the protocols for a TableView, your class is still your class, but you have allowed it to do MORE than just a regular view's range of action
Tobias Schmidt
1,526 PointsOk but what i dont get is - why create a Protocol when You could just type in the functions and properties into the Class?