Mutating self (struct/enum) inside escaping closure in Swift 3.0

后端 未结 3 840
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 08:07

In swift 2.2, We could mutate a struct or enum within a closure, when it was inside a mutating function. But in swift 3.0 its no longer possible. I get the following error

3条回答
  •  心在旅途
    2021-01-04 08:45

    Yeah, you can do something like this.

    struct Point {
    
        var x = 0.0, y = 0.0
    
        mutating func moveBy(x deltaX: Double, y deltaY: Double) {
            x += deltaX
            y += deltaY
    
            test { (a) -> Void in
    
                self.x = Double(a)
            }
        }
    
        mutating func test(myClosure: (_ a: Double) -> Void) {
            myClosure(3)
        }
    }
    

提交回复
热议问题