Can I make #selector refer to a closure in Swift?

后端 未结 11 1806
深忆病人
深忆病人 2020-12-09 15:12

I want to make a selector argument of my method refer to a closure property, both of them exist in the same scope. For example,

func backgroundC         


        
11条回答
  •  眼角桃花
    2020-12-09 15:44

    Swift 5.2.x

    First of all, you need to declare an "easy to use" typealias for your block:

    typealias Completion = () -> ()
    

    Then, you must declare private var to use "as a gate" for your function:

    private var action: Completion?
    

    After that, you should create a function that can be called by your Selector (it accept only string format) and to call private completion:

    @objc func didAction() {
         self.action?()
    }
    

    Finally you can re-write your function (using the new swift syntax) like:

    Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(didAction), userInfo: nil, repeats: false)
    self.action = backToOriginalBackground
    

    P.S.: Remember that your variable (or parameter if you embed it to a function) must be of the same of type declared to your typeAlias so, in our case:

    var backToOriginalBackground: () -> ()
    

    or also:

    var backToOriginalBackground: Completion
    

提交回复
热议问题