UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.