Swift dispatch_after throwing不是前缀一元运算符错误



我有以下代码:

import SpriteKit
import Foundation
class GameScene: SKScene {
    var occupiedCoordinates: NSMutableArray = NSMutableArray()
    func addShape () {
        //...
        shape.position = CGPoint(x:actualX, y:actualY)
        self.occupiedCoordinates.addObject(NSValue(CGPoint:shape.position))
        let halfDuration = random(min: CGFloat(0.5), max: CGFloat(5))
        //...
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2*halfDuration), dispatch_get_main_queue(), ^{
            self.occupiedCoordinates.removeObjectAtIndex(0)
            });
    }
}

我使用了原始剪切的GCD: Dispatch After,在dispatch_after() 的行中得到了以下消息

'^' is not a prefix unary operator

你知道问题出在哪里吗?

^{...}是Objective-C语法。你不需要^

这是将闭包(即objective-c块)传递给swift:中的函数的正确方法

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * halfDuration), dispatch_get_main_queue(), { () -> () in
    self.occupiedCoordinates.removeObjectAtIndex(0)
})

或者你也可以使用这种紧凑的形式:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * halfDuration), dispatch_get_main_queue()) {
    self.occupiedCoordinates.removeObjectAtIndex(0)
}

建议阅读:关闭

最新更新