I want this function be in protocol:
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())? = nil) {
// do some stuff
}
But when I write such protocol:
protocol SomeDelegate {
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())? = nil)
}
I got an error:
Default argument not permitted in a protocol method
I know, I can define the signature in this way:
protocol SomeDelegate {
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())?)
}
But then, I won't be able to call the function missing "completion" word:
slideToRight(currentViewController viewController: vc)
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
In addition to passing arguments to functions via a function call, you can also set default argument values in Python functions. These default values are assigned to function arguments if you do not explicitly pass a parameter value to the given argument. Parameters are the values actually passed to function arguments.
When we define the default values for a function? Explanation: Default values for a function is defined when the function is declared inside a program.
Unfortunately optional arguments are not allowed in protocols, but you can work around this by creating an extension of the protocol:
protocol SomeDelegate {
// with the completion parameter
func slideToRight(currentViewController viewController: UIViewController, completion: ((Bool)->())?)
}
extension SomeDelegate {
// without the completion parameter
func slideToRight(currentViewController viewController: UIViewController) {
slideToRight(slideToRight(currentViewController: viewController, completion: nil))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With