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?