0

I'm trying to show a placeholder image in the case there has not been a picture made:

// Function to create a photo button and image placeholder
    func photoButton(title: String) -> some View {
        VStack {
            // Image placeholder
            if let uiImage = images[title] {
                Image(uiImage: uiImage)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: UIScreen.main.bounds.width * 0.25, height: UIScreen.main.bounds.height * 0.25)
            } else {
                Image(systemName: "camera")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: UIScreen.main.bounds.width * 0.25, height: UIScreen.main.bounds.height * 0.25)
            }
            Spacer()
            Button(action: {
                // Action for camera button
                isShowingCameraView[title] = true
            }) {
                Text(title)
                    .padding()
                    .background(Theme.Colors.MROrange)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }
            .sheet(isPresented: $isShowingCameraView[title]) {
                CameraView(isPresented: $isShowingCameraView[title], image: $images[title])
            }
        }
    }

I'm calling this function from my ContentView like this:

HStack {
                            scanButton(title: "Overeenkomst")
                            .frame(maxWidth: 200, maxHeight: 200)
                            photoButton(title: "Foto client")
                            .frame(maxWidth: 200, maxHeight: 200)
                        }

And at the top my image variable for storing (multiple images):

    @State private var images: [String: UIImage?] = [:]

The errors I'm getting are:

  1. Value of optional type 'UIImage?' must be unwrapped to a value of type 'UIImage'
  2. Coalesce using '??' to provide a default when the optional value contains 'nil'
  3. Force-unwrap using '!' to abort execution if the optional value contains 'nil'

I tried rewriting it to guard, but I got errors about the return statement.

  • 2
    You declared `images: [String: UIImage?]` instead of `images: [String: UIImage]`. Do you have a reason for making the dictionary values `UIImage?` (optional) instead of `UIImage` (non-optional)? – rob mayoff Jul 28 '23 at 00:08
  • Oh wow! Thanks @robmayoff, I've been changing and trying so many things in the hours before posting the question. That totally fixed it! Thanks so much! – Sebas Visser Jul 28 '23 at 10:23

1 Answers1

0

Just do

if let uiImage = images[title] {

  Image(uiImage ?? UIImage(named: "yourPlaceHolderImageName"))
       .resizable()
       .aspectRatio(contentMode: .fit)
       .frame(width: UIScreen.main.bounds.width * 0.25, height: UIScreen.main.bounds.height * 0.25)
}

in case your optional is nil.

devdchaudhary
  • 467
  • 2
  • 13