Capturing a struct reference in a closure doesn't allow mutations to occur

后端 未结 3 977
有刺的猬
有刺的猬 2021-01-14 11:14

I am trying to see if I can use structs for my model and was trying this. When I call vm.testClosure(), it does not change the value of x and I am

3条回答
  •  滥情空心
    2021-01-14 11:36

    Instances of the closure will get their own, independent copy of the captured value that it, and only it, can alter. The value is captured in the time of executing the closure. Let see your slightly modified code

    struct Model
    {
        var x = 10.0
    
        mutating func modifyX(newValue: Double) {
            let this = self
            let model = m
            x = newValue
    // put breakpoint here
    //(lldb) po model
    //▿ Model
    //  - x : 30.0
    //
    //(lldb) po self
    //▿ Model
    //  - x : 301.0
    //
    //(lldb) po this
    //▿ Model
    //  - x : 30.0            
        }
    }
    
    var m = Model()
    
    class ViewModel
    {
    
        let testClosure:() -> ()
    
        init(inout model: Model)
        {
            model.x = 50
            testClosure =
                { () -> () in
                    model.modifyX(301)
            }
            model.x = 30
        }
    }
    
    let mx = m.x
    
    vm.testClosure()
    
    let mx2 = m.x
    

提交回复
热议问题