structgrand-central-dispatchswift2mutating-function

Swift 2: mutating method on struct not working from inside closure


I'm trying to call a mutating method on one of my structs from within a closure. It's not working.

I'm scheduling the closure to be called from dispatch_after. I'm getting the error message Partial application of 'mutating' method is not allowed.

This was working in Swift 1.2. Not in Swift 2. The error appeared after updating. Here's a stand-alone example that will show the error in a Playground.

struct MutationTest {

    var timestamp: Int = 0

    mutating func changeTimestamp () {
        timestamp += 1 //NO ERROR HERE
    }

    mutating func callChangeTimeStamp() {
        changeTimestamp() //NO ERROR HERE
    }

    mutating func scheduleCallChangeTimestamp() {
        let highQConstant = DISPATCH_QUEUE_PRIORITY_HIGH
        let highQ = dispatch_get_global_queue(highQConstant, 0)
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC))
        dispatch_after(time, highQ, callChangeTimeStamp) //ERROR HERE
    }

}

By the way, I get the exact same error if I change the changeTimestamp method to:

    mutating func changeTimestamp () {
        self = MutationTest(timestamp: timestamp + 1)
    }

Solution

  • This seems to work ok:

    dispatch_after(time, highQ, { self.callChangeTimeStamp() })