2
votes

I'm learning about weak vs strong and still don't fully grasp it. How can I declare weak response in the following function so I don't have a retained cycle?

AF.request(url, method: .get).validate().responseData { [weak self] response in
    guard let data = response.data else {
        completionHandler(.failure(.apiFailed))
        return
    }

    do {
        let decodedData = try JSONDecoder().decode(T.self, from: data)
        
        DispatchQueue.main.async {
            completionHandler(.success(decodedData))
        }
    } catch {
        completionHandler(.failure(.corruptedData))
        return
    }
}

Right now I have an xcode warning saying:

Variable 'self' was written to, but never read

enter image description here

How can I read it using weak?

1

1 Answers

0
votes

A retain cycle can only happen when an object ends up owning itself through a series of owning (strong) relationships, usually through one or more objects in a chain. For instance, if an object A has an owning relationship to an object B, and object B has an owning relationship to object A, then A ends up with an owning relationship to itself, which can prevent it from being deallocated. Breaking this cycle requires one of these objects to change its ownership to a non-owning relationship (weak, or unowned). (This can also happen if A stores a strong reference directly to itself, or if the chain goes A -> B -> C -> D -> A, or any number of other configurations.)

In the context of callbacks like this, the risk you run into with retain cycles is that if object A stores a closure which has a strong (the implicit default) reference to A somewhere inside of it, it cyclicly refers to itself.

However: this only happens if the closure actually has a reason to maintain a strong reference to A in the first place. Your closure, for instance, never refers to self inside of it, so would have no reason to maintain a reference to self in the first place. Closures only maintain references (or "close over", hence "closure") to the things used inside of them — and self is not.

Hence the warning: you are never "reading" (i.e. accessing) self anywhere inside of the closure, so the [weak self] is unnecessary altogether.