不能得到简单的 Swift #selector 来编译

Can't get simple Swift #selector to compile

我已经尝试了所有我能想到的排列方式,并阅读了各种关于 Swift #selectors 的文档,但我一无所获。这是代码:

class AFSelectionState: GKComponent {
    let clearSelectionIndicator: (Set<Int>?) -> Void
    let setSelectionIndicator: (Set<Int>) -> Void

    init(setSelectionIndicator: @escaping (Set<Int>) -> Void, clearSelectionIndicator: @escaping (Set<Int>?) -> Void) {
        self.clearSelectionIndicator = clearSelectionIndicator
        self.setSelectionIndicator = setSelectionIndicator
    }
}

class GameScene: SKScene, SKViewDelegate {
    var selectionState: AFSelectionState!

    override func sceneDidLoad() {
        ...

/****************** Compiler errors coming up ****************
 **
 ** Tried #selector(setSelectionIndicator_(_:))
 ** Got "Cannot convert value of type 'Selector' to expected
 ** argument type '(Set<Int>) -> Void'"
 ** From what I've read, the above should be working, but you know
 ** how it is when people say "should".
 **
 ** Tried #selector(setSelectionIndicator_(_:) -> ())
 ** Got "Expected type before '->'".
 **
 ** Tried all sorts of other stuff. There's something about
 ** selectors that I'm missing.
 ** 
 *********************** Et cetera! *************************/

        selectionState = AFSelectionState(

            setSelectionIndicator: #selector(setSelectionIndicator_(_:)),
            clearSelectionIndicator: #selector(clearSelectionIndicator_(_:))

        )

        ...
    }
}

extension GameScene {
    @objc func setSelectionIndicator_(_ selectedIndexes: Set<Int>) -> Void {
        ...
    }

    @objc func clearSelectionIndicator_(_ indexes: Set<Int>?) -> Void {
        ...
    }
}

Selector 基本上是一个字符串,而不是闭包、块或任何可以执行的代码。要实现您的需要,请尝试以下操作:

selectionState = AFSelectionState(

    setSelectionIndicator: self.setSelectionIndicator_,
    clearSelectionIndicator: self.clearSelectionIndicator_

)

P.S。确保你没有用这个创建引用循环

这是正确的语法:

selectionState = AFSelectionState(setSelectionIndicator: setSelectionIndicator_, clearSelectionIndicator: clearSelectionIndicator_)

您混合了选择器和闭包。查看 link:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html