Skip to content

Latest commit

 

History

History
2 lines (2 loc) · 1.11 KB

File metadata and controls

2 lines (2 loc) · 1.11 KB
  • I've talked before about what Protocols are and I've actually referenced them a lot throughout this roadmap, but now we'll do a deeper dive inside this concept. First of all, a Protocol defines a blueprint of methods or properties thatcan then be adapted by classes (or other types). One of the biggest benefits of using Protocols is actually the fact that multiple classes can abide by a single protocol. Let's suppose we have two objects struct Dog { var breed: Labrador} and struct Cat { var breed: British Shorthair}. Now, let's print their names. You'd have to do something like func printOut(dog: Dog){ dog.breed } and func printOut(cat: Cat){ cat.breed }. But, if you'd use a protocol, for example Protocol Printing { var name: String { get } }, and then you define the structs as protocolsof Printing: struct Dog: Printing { var name: String } and struct Cat: Printing { var name: String }, you could then use a single function to print both of their names, like so: `func printOut(object: Printing) { print(object.name) }.