NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Binding with optional struct

Forums > SwiftUI

I get the error "Value of optional type 'Photo?' must be unwrapped to refer to member 'name' of wrapped base type 'Photo'" when I try to send a optional struct on a binding of a TextField.

The Photo struct:

import Foundation

struct Photo: Identifiable {
    var id: UUID
    var name: String
    var data: Data
}

The content view code example:

import SwiftUI

struct ContentView: View {
    @StateObject var viewModel = ContentViewViewModel()

    private var photos = [
        Photo(id: UUID(), name: "Exclamation", data: (UIImage(systemName: "exclamationmark.triangle")?.jpegData(compressionQuality: 1))!),
        Photo(id: UUID(), name: "Circle", data: (UIImage(systemName: "circle.fill")?.jpegData(compressionQuality: 1))!)
    ]

    var body: some View {
        VStack {
            DetailView(viewModel: viewModel)
        }
        .onAppear {
            viewModel.selectedPhoto = photos[0]
        }
    }
}

The view model code example:

import Foundation

@MainActor
final class ContentViewViewModel: ObservableObject {
    @Published var photos = [Photo]()
    @Published var selectedPhoto: Photo?
}

The detail view code example (that uses the content view's view model):

import SwiftUI

struct DetailView: View {
    @ObservedObject var viewModel: ContentViewViewModel

    var body: some View {
        TextField("Photo name here...", text: $viewModel.selectedPhoto.name)
    }
}

Note that for some reasons I need the selectedPhoto property be optional.

Suggestions to solve it?

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.