Swift - scheduledTimerWithTimeInterval - NSInvocation

Gui*_*uig 5 timer swift

我想在将来安排一个函数调用.我正在使用Swift.

我想回调一个私有的方法并返回一个Promise(来自PromiseKit)

我见过的所有例子都使用了

NSTimer.scheduledTimerWithTimeInterval(ti: NSTimeInterval, target: AnyObject, selector: Selector, userInfo: AnyObject?, repeats: Bool)
Run Code Online (Sandbox Code Playgroud)

精细.我试过了

NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "connect", userInfo: nil, repeats: false)
Run Code Online (Sandbox Code Playgroud)

那失败了No method declared with Objective-C selector 'connect'.

什么是Objective-C在这做什么?

无论如何,建议我@objc在我的方法前添加connect.精细.好吧,我不能,因为显然Method cannot be marked @objc because its result type cannot be represented in Objective-C

如果我想使用Objective-C我不会写Swift ...

还有一个scheduledTimerWithTimeInterval

NSTimer.scheduledTimerWithTimeInterval(ti: NSTimeInterval, invocation: NSInvocation, repeats: Bool)
Run Code Online (Sandbox Code Playgroud)

但是从我所读到NSInvocation的不是斯威夫特的事情......

所以我最终创建了一个包装器,除了调用connect和返回VoidObjective C可以理解之外什么也没做.它有效,但感觉非常愚蠢.有更好的Swift方式吗?

额外奖励:为什么javascript可以这样做,setTimeout(this.connect, 1)而且Swift没有我可以找到的内置方式?

myg*_*gzi 4

从 iOS 10 和 Swift 3 开始,可以将 (NS)Timer 与块闭包一起使用,从而避免在计时器触发时调用 Objective-C 选择器:

    if #available(iOS 10.0, *) {
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false, block: { (Timer) in
            self.connect() // per the OP's example
        })
    }
Run Code Online (Sandbox Code Playgroud)

除了避免使用@objc装饰器之外,使用此技术还允许您调用包含非 Objective-C 兼容参数类型(例如枚举和可选值)的方法。

回复:setTimeout(this.connect, 1)从 Javascript 来看,如果不需要取消它,在 Swift 3 中更直接的类比可能是:

DispatchQueue.Main.asyncAfter(deadline: .now() + 1.0, execute { self.connect() })
Run Code Online (Sandbox Code Playgroud)

考虑到您实际上可以选择在哪个线程上运行,这非常接近;-)