Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift How to create a Protocol instance

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?

like image 703
Guster Avatar asked Sep 14 '25 08:09

Guster


1 Answers

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")
   }
}
like image 88
HorseT Avatar answered Sep 16 '25 22:09

HorseT