Knowledge Drilling
Knowledge Drilling

Reputation: 1036

How can i make protocol implementation as argument of function

How do i create Protocol as an argument of function.

In Android java, we can make an argument of interface like this.

Button.setOnClickListener(new View.OnClicklistener()
{
    @Override
    public void onClick(View v)
    {

    }
});

But how do i do same thing in Swift. For example, i have following Protocol, how can i pass protocol while constructing it.

protocol ButtonListener
{
    func onClick()
}

Upvotes: 2

Views: 464

Answers (3)

ikbal
ikbal

Reputation: 1250

You can give it by protocol.

protocol ButtonListener {}

extension ButtonListener where Self: UIView {
    func btnClick() {
        // print func
    }
}

Upvotes: 0

Sweeper
Sweeper

Reputation: 271625

In Swift, these single-method protocols, as event handlers are not necessary. In Swift, you can create any kind of closure type you want.

Your onClick method can be represented by the closure type () -> Void (accepts no parameters and returns Void). Instead of setOnClickListener as a method, you can just declare onClick as a property:

var onClick: (() -> Void)?

And then you can set it just like you would with any other property:

onClick = {
    print("I am clicked!")
}

To call onClick, you can unwrap it first to make sure it's not nil:

if let onClick = self.onClick {
    onClick()
}
// or
onClick?()

If you are familiar Java 8, closure types are kind of like functional interfaces, except you get more freedom with closure types. Consumer<String> would correspond to (String) -> Void, Function<String, Integer> would correspond to (String) -> Int, etc.

Upvotes: 0

Ahmad F
Ahmad F

Reputation: 31645

It seems that there is a misunderstanding for what you should use to achieve it. Probably you want to pass a closure as a parameter to the function.

Citing from the Swift programming language - Closures:

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

Example:

protocol Foo {
    func myFunc(onClick: (_ myView: UIView) -> Void)
}

class MyClass: Foo {
    func myFunc(onClick: (UIView) -> Void) {
        // ...
    }
}

Here we have a Foo protocol contains myFunc which has a closure parameter of type (UIView) -> Void.

Therefore:

let object = MyClass()

object.myFunc { view in
    // you can access `view` here as:
    view.backgroundColor = ...
    view.frame = ...
}

Upvotes: 1

Related Questions