Would compiler optimise this?

I'm dealing with an exclusive memory access crash. The infamous "Simultaneous accesses to..." message.

I have a following piece of code that is problematic:

self.observer = nil

Since observer is a closure, its deallocation can trigger a chain reaction that eventually attempts to access self.observer, violating Swift's Exclusive Access to Memory (SE-0176).

The solution is simple - I just have to retain the value until after the property is nilled out:

    if let observer = self.observer {
        self.observer = nil
        _ = observer

This seems to solve the problem, but I'm worried if the compiler will attempt to optimise something here, since local variable observer is not really used, when compiling with optimisations.

Do I have a guarantee here that the local observer will be retained until end of the scope, even though it's not actually used?

I believe you could use withExtendedLifetime.


Thank you, that seems to be exactly what I need!

Terms of Service

Privacy Policy

Cookie Policy