Sobes.tech
Junior — Senior

Detection and elimination of memory leaks in asynchronous Swift operations

livecode

Task condition

The task is to analyze the provided asynchronous Swift code, identify potential memory leaks, and make corrections to ensure proper resource deallocation.

class DataProcessor {
    func process(data: String, completion: @escaping (String) -> Void) {
        DispatchQueue.global().async {
            let result = data.uppercased()
            DispatchQueue.main.async {
                completion(result)
            }
        }
    }
}

var handler: DataProcessor? = DataProcessor()
handler?.process(data: "hello") { result in
    print(result)
    handler = nil  // releasing the object after use
}

In this example, it is important to pay attention to capturing self (or the handler variable) inside the closure and ensure that after the operation completes, the object is properly deinitialized to avoid lingering references in memory.