Reputation: 1821
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?
Upvotes: 4
Views: 7300
Reputation: 6592
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")
}
}
Upvotes: 13