skip to Main Content

I see this code in telegram open source app , how to create function like this and where is this application codes? this class is final and don’t have delegate our protocol

 var vote:(MessageId, Data?) -> Void = { _, _ in }

2

Answers


  1. I don’t know where you saw this, but this is closure variable. You can call it on class/struct where this vote is declared and then code inside closure will be called with certain parameters.

    For example if you assign vote like this

    someClass.vote = { messageId, data in // name parameters or not: _,data ; messageId,_ ; _,_
        print("Voted")
    }
    

    then if vote is called from inside of the class/struct

    vote(someMessageId, someData)
    

    "Voted" gets printed.


    So, this is useful delegate pattern replacement which allows you to declare from one class/struct what will happen when this closure gets called from another class/struct without declaring any protocol, assigning delegate and having extra methods.

    Login or Signup to reply.
  2. It’s a closure variable that you can assign your own closure to and your code will be executed whenever vote is called

    var vote:(Int, String?) -> Void = { _, _ in }
    
    vote = { (id, data) in print("(id) (data)") }
    
    vote(32, "Hello")
    

    Note that I changed the parameter types in my example since I am not familiar with Telegram classes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search