Hi!
Let's start with what is UIAlertAction class. As you can see the it takes three agruments
(title: String?, style: UIAlertAction.Style, handler: ((UIAlertAction) -> Void)?)
First one is title of type String?.
Second one is style which is enum of UIAlertActoin.Style type
And the third one is handler which is of type ((UIAlertAction) -> Void)?
The last one is handler that can be used as a closure. So you don't need to create separate function of that type and then pass it here, but you can directly put the unnamed function i.e. created on spot in a closure. So this is the handler by itself as well.
{ [weak self, weak ac] _ in // self is a ViewController class that calls submit(answer)
guard let answer = ac?.textFields?[0].text else { return } // ac retrieves the answer from the textField
self?.submit(answer) // ViewController sumbit answer
}
to fully understand about weak stuff you need to know how ARC(Automatic Reference Counting) works. To put it simple ARC makes sure memory managment works properly i.e. objects are released from memory. For that you need to mark some items used in closures as weak.
A weak reference is a reference that doesn’t keep a strong hold on the instance it refers to, and so doesn’t stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing the weak keyword before a property or variable declaration.
Because a weak reference doesn’t keep a strong hold on the instance it refers to, it’s possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference to nil when the instance that it refers to is deallocated. And, because weak references need to allow their value to be changed to nil at runtime, they’re always declared as variables, rather than constants, of an optional type.
more you can find here. https://docs.swift.org/swift-book/documentation/the-swift-programming-language/automaticreferencecounting#Resolving-Strong-Reference-Cycles-Between-Class-Instances
A closure can capture constants and variables from the surrounding context in which it’s defined. The closure can then refer to and modify the values of those constants and variables from within its body, even if the original scope that defined the constants and variables no longer exists.
in simple words one class refers to second class and second class refers to first class. So keeping both alive even when code already finished. Creating kind of circle. To break that circle you mark one class weak and as soon as one class stops existing the other destroyed and all memory freed.