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
Reed Carson
8,306 PointsWhy are protocols useful
I understand how to write them and use them, but I dont understand what they are useful for. It seems that they are only useful from the perspective that other people might have to work with your code.
Like instead of making my class conform to a protocol Ive written, why cant I just add whatever functions and variables I want without having a protocol at all?
Toby Morgan
iOS Development Techdegree Graduate 23,133 PointsI'm new to Swift Protocols too, but it seems to me that a key benefit is that you can use protocols as function parameter types and return types, and since you aren't forced to use them hierarchically (as you would with inheritance) you can say:
"the type passed in to my function can be any type as long as it implements the requirements of this protocol"
To me thats hugely flexible. I've only just started using it in my projects, but I think its pretty exciting.
1 Answer
Greg Kaleka
39,021 PointsHey Reed,
Swift is a Protocol-Oriented programming language. They are incredibly important to the language. Object Oriented design is a very powerful, well-established design pattern, and it is and will continue to be heavily used in Swift, but it has problems, and Swift has taken steps to move away from some of those problems.
Even when you're programming alone, protocols can be very helpful. For example, you can use a protocol as an argument type for a method, and then pass multiple different types into it, so long as they each adhere to the protocol in question. If you haven't already, check out the Swift 2 Protocols course. You'll see some examples of protocols that should help demonstrate why they're useful.
Also, Apple had an excellent WWDC talk on this topic in 2015. I strongly recommend watching it.
Happy coding,
-Greg
Reed Carson
8,306 Pointsoh no lol. I tried to watch that video already but the guy was too awkward for me to watch it
Greg Kaleka
39,021 PointsHeh welcome to software development :P.
jcorum
71,830 Pointsjcorum
71,830 PointsSuggest you look at:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.htmlIf you've done Java programming, you probably have your own feelings whether or not interfaces are useful, and why! Protocols are SWIFT's interfaces.