I'm pretty new in the iOS development world and I'm trying to understand protocols in Swift. Here's my code:
protocol Animal {
func printFood()
}
struct Rabbit: Animal {
func printFood() {
print("carrot")
}
}
struct Sheep: Animal {
func printFood() {
print("grass")
}
}
I have this very simple protocol with these two structs conforming to it. I wrote these two functions:
func printAnimalFood<A: Animal>(_ animal: A) {
animal.printFood()
}
func printAnimalFood(_ animal: Animal) {
animal.printFood()
}
Is this the same way to write the same thing? Or not? In many examples I see a lot of functions written in the first way but I don't understand why since I can use the second way and obtain the same result. Why should I introduce a generic type parameter since I can directly use the protocol as parameter? Is there any subtle difference? Are there some situations in which I should use the first "syntax" over the second one and vice versa?
I tried to execute both the functions and, as expected, the printed result is the same, with no difference.
Protocols as Parameters: When you define a function or method that takes a protocol as a parameter, it means that any value passed to that parameter must conform to the specified protocol. This allows you to write more flexible and reusable code.
Protocols as Generic Types: When you use a protocol as a generic type, it means that the generic type placeholder can be any type that conforms to the specified protocol. This allows you to create more generic and flexible code that can work with different types that share common behaviors.