WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 77 - Help storing image as Data in struct

Forums > 100 Days of SwiftUI

I'm attempting to store a name and image data into a struct of people for the Day 77 milestone project, and getting an error stating:

Value of optional type 'Data?' must be unwrapped to a value of type 'Data'

I'm sure I'm missing something obvious, but can't seem to put my brain on exacty why I can't load the UIImage data into the "people" array from the viewModel.

Thanks for any pointers!

The Struct is as follows:

struct SpecificPerson: Identifiable {
    var id = UUID()
    var name: String
    var image: Data?

    init(id: UUID, name: String, image: Data) {
        self.id = id
        self.name = name
        self.image = image
    }
}

The AddPersonView is:

struct AddPersonView: View {
    @Environment(\.dismiss) var dismiss

    @State private var pickerItem: PhotosPickerItem?
    @State private var selectedImage: Image?
    @State private var uiSelectedImage: Data?

    @State private var selectedImageName: String = ""

    @Bindable var viewModel: PeopleViewModel

    var body: some View {
        VStack {
            if let selectedImage {
                selectedImage
                    .resizable()
                    .scaledToFit()

                Text("Please enter a name for this person:")
                    .padding()
                TextField("Enter Name", text: $selectedImageName)
                    .textFieldStyle(.roundedBorder)
                    .padding(.horizontal)

                Button("Save") {
                    let personToAdd = SpecificPerson(id: UUID(), name: selectedImageName, image: uiSelectedImage)
                    viewModel.people.append(personToAdd)
                    dismiss()
                }
            } else {
                PhotosPicker("Select a Photo", selection: $pickerItem, matching: .images)
            }
        }
        .padding()
        .onChange(of: pickerItem) {
            Task {
                if let data = try await pickerItem?.loadTransferable(type: Data.self) {
                    uiSelectedImage = data
                }
            }
        }
    }
}

And the viewModel:

@Observable
class PeopleViewModel {
    var people = [SpecificPerson]()
}

   

It's because in this line:

let personToAdd = SpecificPerson(id: UUID(), name: selectedImageName, image: uiSelectedImage)

you are supplying uiSelectedImage for the third parameter. uiSelectedImage is of type Data? but the signature of SpecificPerson.init calls for Data:

init(id: UUID, name: String, image: Data)

So you should be calling it with uiSelectedImage unwrapped. How exactly you do that (e.g., force unwrap, nil coalescing with a default value, etc) depends on how you want it to work in the event that uiSelectedImage is nil.

1      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.