【问题标题】:Can't get simple Swift #selector to compile无法编译简单的 Swift #selector
【发布时间】:2017-12-30 15:12:43
【问题描述】:

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

【问题讨论】:

    标签: swift syntax compiler-errors selector


    【解决方案1】:

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

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

    附:确保你不要用这个创建参考循环

    【讨论】:

      【解决方案2】:

      这是正确的语法:

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

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

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

      【讨论】:

        猜你喜欢
        • 2014-08-15
        • 2012-07-26
        • 2018-02-17
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-07
        相关资源
        最近更新 更多