4

I am a Android developer, and I'm very new to Swift so please bear with me. I am trying to implement callback functions with Protocol in Swift. In Java I can create an Interface and make it an instance without linking it to any implementing class so that I can pass it around, for example:

public interface SomeListener {
    void done(); 
}

SomeListener listener = new SomeListener() {
    @Override
    public void done() {
        // do something
    }
}
listener.done();

How can I do it with Protocol in Swift? Or can it actually be done?

2

1 Answer 1

13

That`s a way you can implement a protocol. Its like the delegate pattern in ObjC

protocol DoneProtocol {
    func done()
}

class SomeClass {
    var delegate:DoneProtocol?

    func someFunction() {
        let a = 5 + 3
        delegate?.done()
    }
}

class Listener : DoneProtocol {
   let someClass = SomeClass()

   init() {
       someClass.delegate = self
       someClass.someFunction()
   }
   // will be called after someFunction() is ready
   func done() {
       println("Done")
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just did some research, so apparently Swift doesn't have an anonymous class behavior yet, i guess this is the only way, thanks!
@gricher Java uses anonymous classes primarily as a way around the fact that the language doesn't support closures (think inline anonymous functions) Since Swift does support closures there is much less need for anonymous classes, and the syntax winds up being much cleaner besides.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.