无法通过简单的Swift #selector进行编译

时间:2017-12-30 15:12:44

标签: swift syntax compiler-errors selector

我已经尝试了我能想到的每一种排列,并阅读了各种关于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 {
        ...
    }
}

2 个答案:

答案 0 :(得分:3)

@functionReturningFunctionWithOneArg(any, "args") 基本上是一个字符串,不是闭包,块或任何可以执行的代码。要实现您的需求,请尝试以下方法:

Selector

P.S。确保您不使用此

创建参考周期

答案 1 :(得分:2)

这是正确的语法:

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

您混合了选择器和闭包。看看链接:

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