Search code examples
iosswiftclosuresunsafeweak

What is difference between "[self] in" & "[weak self] in" in Swift?


I just found out that I can write "[self]" in the closures instead of [weak self] in but I'm not sure if it is safe or not.

more detail:

Before:

func roundShape(corners: CACornerMask, radius: CGFloat) {
        DispatchQueue.main.async { [weak self] in
            layer.cornerRadius = radius
            layer.maskedCorners = corners
        }
    }

Now:

 func roundShape(corners: CACornerMask, radius: CGFloat) {
      DispatchQueue.main.async { [self] in
           layer.cornerRadius = radius
           layer.maskedCorners = corners
      }
  }

So please light me up if you know the difference.


Solution

  • Writing [self] is same as leaving the closure as it is meaning it could cause retain cycle unlike [weak self] , BTW no need for any of them with DispatchQueue.main.async { as GCD queues don't hold a strong reference to self