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

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?

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.