Dan lost focus for a second....
How does "guard let image = imageView.image?.jpegData...know which photo is being used to convert into jpeg?
Let's look at your code:
@objc func shareTapped() {
guard let image = imageView.image?.jpegData(compressionQuality: 0.8) else {
print("No image found")
return
}
Your application probably is composed of many views. An application view, a button bar view, a navigation view, etc. I imagine my applications being made of Lego bricks that I can snap into various shapes to make awesome products.
One of your views is probably called ImageView
and is a subcomponent in someother view, perhaps called ProductView
. This view object may have several internal @State variables. It may have several parameters, or calculated properties. From the snippet you provide, one of these properties is named image
and it's an optional.
The ProductView
may attempt to create a subcomponent of type ImageView
, and gives it the name imageView
. To create this subcomponent, it provides a URL to an internet jpeg, or the URL to a local jpeg in the Photos library, or a URL to a photo in the application's bundle.
You have many options for providing a jpeg, but the fundamental condition exists for each option. You may TRY to create the ImageView
subcomponent with an image, but that image file may not really exist!
At somepoint however, your view structure has an ImageView
on screen, and that view is named imageView
. As stated earlier, this view has an image property that may, or may NOT, contain a valid image.
func shareTapped()
In the code snip you provided, the function shareTapped()
is telling the compiler that it absolutely requires a bonafide image to proceed. Therefore, it stations a guard at the entrance. The guard opens the imageView
and peeks inside. There it finds the optional image
property. IF that property actually contains a valid image object, the guard hands it over to the local variable named image
and allows the function to proceed.
Otherwise it boots the imageView
in the butt, denies entry, and prevents the function from trying to run with a non-existant image.