Default argument not allowed in protocols
Try this Swift code in a Playground and observe what is compiler is complaining about.
protocol RoastCoffee {
func roastingComplete(with smellsGood: Bool = true) //Error: Default argument not allowed in protocols
}
Were you able to find out any details reason for why Swift compiler is not allowing programmers to add a default value for the parameter ? Frankly, neither do I, but it makes sense since protocol is an agreement between the defining party and the implementation, hence declaring a default value for the parameters to be passed makes it less flexible for the implementer in my opinion.
Whether what Apple did is correct or not is up for debate, but lets try to see whether there is a way around it. The solution is simple and direct, you need to make use of the extension and add your parameter in that, such as below.
protocol RoastCoffee {
func roastingComplete(with smellsGood: Bool)
}
extension RoastCoffee {
func roastingComplete(with smellsGood: Bool) {
self.roastingComplete(with: true)
}
}
class CoffeeConsumer : RoastCoffee { // Compiler will not complain about implementing roastingComplete hence it already has a default method. But you can override it if you need.
func roastingComplete(with smellsGood: Bool?) {
print("coffee smells good \(String(describing: smellsGood))")
}
}
Whoa ... that's it !
Add new comment