Categories
Mastering Development

Escaping closure captures mutating ‘self’ parameter (SWIFT 5)

I’m trying to make a thread-safe struct using the @propertyWrapper, but I have such an error from the playground when I’m setting a value.
The error goes, only if I change the async to sync, but I just need to have async function

@propertyWrapper
struct SafeThread<Value>{

    private let queue = DispatchQueue(label: "sellQueue",attributes:.concurrent )
    private var value: Value
    
    
    init (wrappedValue: Value){
        self.value = wrappedValue;
    }
    
    
    var wrappedValue :Value {
        get { queue.sync { value } }
        set { queue.async(flags: .barrier) { self.value = newValue } } // there an error 
        
    }
}

And class where I want to use it :

class Safe{
@SafeThread var foo = 0;
    
func threadSafetyExperiment() {
    
    DispatchQueue.global().sync {

        DispatchQueue.concurrentPerform(iterations: 1_000) { _ in
            self.foo += 1
        }
        print(self.foo)
    }
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *