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

后端 未结 11 1810
深忆病人
深忆病人 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:33

    @werediver's answer is excellent. Here's an update that allows you to call it as a function.

    import Foundation
    
    public extension Selector {
      /// Wraps a closure in a `Selector`.
      /// - Note: Callable as a function.
      final class Perform: NSObject {
        public init(_ perform: @escaping () -> Void) {
          self.perform = perform
          super.init()
        }
    
        private let perform: () -> Void
      }
    }
    
    //MARK: public
    public extension Selector.Perform {
      @objc func callAsFunction() { perform() }
      var selector: Selector { #selector(callAsFunction) }
    }
    

    You need to manage strong references to Selector.Performs. One way to do that is to subclass UIKit classes that were designed to work with target-action:

    /// A `UITapGestureRecognizer` that wraps a closure.
    public final class TapGestureRecognizer: UITapGestureRecognizer {
      public init(_ perform: @escaping () -> Void) {
        self.perform = .init(perform)
        super.init(target: self.perform, action: self.perform.selector)
      }
    
      public let perform: Selector.Perform
    }
    
    let tapRecognizer = TapGestureRecognizer { print("

提交回复
热议问题