Swift单例类中imagePickedBlock属性类型咨询
imagePickedBlock in CameraHandler? Great question—let’s break this down clearly using your code as a reference. First, here’s the key snippet from your singleton:
class CameraHandler: NSObject, UIImagePickerControllerDelegate { static let shared = CameraHandler() //MARK: Internal Properties var imagePickedBlock: ((UIImage) -> Void)? ///// What kind of property is THIS ??? func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { self.imagePickedBlock?(image) } else{ print("Something went wrong") } } }
And your calling code:
CameraHandler.shared.imagePickedBlock = { (image) in /* get your image here */ print("Got image!!!!") }
Now, let’s define exactly what imagePickedBlock is:
It’s an optional stored closure property
The type((UIImage) -> Void)?tells us:- The core type is a closure that accepts a single
UIImageparameter and returns no value (marked by-> Void). - The trailing
?makes it an optional, so it starts asniluntil you assign a closure to it (like you do in your calling code). - Since it’s declared with
varinstead oflet, it’s mutable—you can reassign different closures to it at runtime if needed.
- The core type is a closure that accepts a single
Functionally, it’s a callback mechanism
This property exists to handle asynchronous results from the image picker. Since waiting for a user to select an image isn’t an immediate action, the closure acts as a "callback": once the user finishes picking a photo, theimagePickerController(_:didFinishPickingMediaWithInfo:)method triggers the closure, passing the selected image directly to the code that needs it. The?inself.imagePickedBlock?(image)safely runs the closure only if you’ve assigned one (avoiding crashes if it’s stillnil).
In short, it’s a mutable, optional stored property that holds a closure for asynchronous image selection callbacks.
内容的提问来源于stack exchange,提问作者Mudith Chathuranga Silva

