Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare protocol function with default argument values

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)
like image 581
Roman Vygnich Avatar asked Mar 05 '18 16:03

Roman Vygnich


People also ask

How a function is declared using default values for its arguments?

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.

Can we give default value to arguments?

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.

Can we define the default values for a function?

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.


1 Answers

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))
    }
}
like image 125
Sweeper Avatar answered Sep 27 '22 22:09

Sweeper