Home > Net >  How to accept function as a parameter in function
How to accept function as a parameter in function

Time:01-25

I need to accept function as a parameter after accepting function I want that function to be done on viewcontroller with self code below for better understanding

private func addSwipeControllerLeft(name: String, color: UIColor) -> UISwipeActionsConfiguration {
  let action = UIContextualAction(
    style: .normal,
    title: name
  ) { [weak self] (action, view, completionHandler) in
    self?.handleMarkAsFavourite()  // I need to create function with accepts another function as a parametre
    completionHandler(true)
  }
}

I tried generics but it returns an error Value of type 'FeedViewController' has no member 'T'

private func addSwipeControllerLeft2<T>(name: String, color: UIColor, pFunction: T) -> UISwipeActionsConfiguration {
  let action = UIContextualAction(
    style: .normal,
    title: name
  ) { [weak self] (action, view, completionHandler) in
    self?.T
    completionHandler(true)
  }
}

any solutions ?

CodePudding user response:

There is no need for a generic Type here. Add your desired function signature to addSwipeControllerLeft2s signature and call it inside your closure.

                                                                // declare the signature here
private func addSwipeControllerLeft2(name:String,color:UIColor, pFunction: @escaping ()->Void) -> UISwipeActionsConfiguration{
    let action = UIContextualAction(style: .normal, title: name) { [weak self] (action, view, completionHandler) in
        pFunction() // invoke it here
        completionHandler(true)
    }
}

you could call it this way:

private func TestFunc(){
    
}

func TestAddSwipe(){
    // you can pass any function to pFunction: you want as long as it 
    // satisfies the signature ()->Void
    addSwipeControllerLeft2(name: "", color: .red, pFunction: TestFunc)
}

CodePudding user response:

Calling a passed function on self cannot be done in this way, but if you pass the ViewController function as a parameter, it will be called on self:

class ViewController: UIViewController {
    private func addSwipeControllerLeft2(name: String, color: UIColor, function: @escaping () -> Void) -> UISwipeActionsConfiguration{
        let action = UIContextualAction(style: .normal,
                                        title: name) { (action, view, completionHandler) in
            function()
            completionHandler(true)
        }
        return UISwipeActionsConfiguration(actions: [action])
    }
    
    private func handleMarkAsFavourite() {
        print("Called on", self)
    }
}

Example:

addSwipeControllerLeft2(name: "Test", color: .red, function: self.handleMarkAsFavourite)
  • Related