I'm working on calling an animation in Swift and I'm a bit confused with using [weak self]
in the nested block. I saw some other posts related to this question, but it confused me because some say they need the weak self
, and some don't.
My animation block is something like this.
func showFocusView() {
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut]) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.focusView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
strongSelf.focusView.alpha = 1
} completion: { animated in
if !animated {
return
} else {
UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseInOut]) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.focusView.transform = .identity
} completion: { animated in
if !animated {
return
} else {
UIView.animate(withDuration: 1.5, delay: 0, options: [.curveEaseInOut]) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.focusView.alpha = 0.5
} completion: { animated in
if !animated {
return
} else {
UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseInOut]) { [weak self] in
guard let strongSelf = self else { return }
strongSelf.focusView.alpha = 0
}
}
}
}
}
}
}
}
My assumption is that sing the animate method's animations block allows escaping,
class func animate(withDuration duration: TimeInterval,
animations: @escaping () -> Void,
completion: ((Bool) -> Void)? = nil)
I made each animation block a weak self, and when the animated block is called, it is not sure if the self still exists or not. So, I created a strongSelf variable using a guard statement. I did that for every block to make sure the existence of the self, but should I include them in every block, or I shouldn't? I'd like to know why I need / don't need the block....