0

I have a SwiftUI view that uses a date picker.

I am trying to update my model via the date picker. The model is "Injected" via swinject, however I feel like something is slightly missing.

The error is:

Cannot convert value of type 'Published<Date>.Publisher' to expected argument type 'Binding<Date>'

My view has the following code:

@Injected var viewModel: SignupViewModel
...
DatePicker("",selection: viewModel.$birthday, displayedComponents: [.date]).datePickerStyle(.wheel).environment(\.locale, Locale.init(identifier: "en-GB"))
                .padding()

Model

import Foundation

public class SignupViewModel: ObservableObject {
    
    @Published var birthday: Date = Date()

    @Injected var services: Services

}

The @Injected code is a property wrapper as follows

import Foundation
import Swinject

public struct Injection {
    public static let container = Container()
}

@propertyWrapper public struct Injected<Dependency> {
    public let wrappedValue: Dependency
 
    public init() {
        self.wrappedValue = Injection.container.resolve(Dependency.self)!
    }
}

My container in the App

    public init() {
        Injection.container.register(SignupRouter.self) { _ in
            return SignupRouter()
        }
        Injection.container.register(SignupViewModel.self) { _ in
            return SignupViewModel()
        }

    }

I have tried both $viewModel.birthday and viewModel.$birthday

As a side note, this does work if I change @Injected to @ObservedObject and create the model, so it's as if the @Injected isn't seeing the "type"?

I appreciate this is a gap in my knowledge so any help would be appreciated.

mickeysox
  • 159
  • 2
  • 14

1 Answers1

0

Solved below.

I actually pulled this from Factory which I think I am going to start using instead of trying to hack around with Swinject.

@propertyWrapper public struct Injected<T>: DynamicProperty where T: ObservableObject {
    @StateObject private var dependency: T
    public init() {
        self._dependency = StateObject(wrappedValue: Injection.container.resolve(T.self)!)
    }
    public var wrappedValue: T {
        get { return dependency }
    }
    public var projectedValue: ObservedObject<T>.Wrapper {
        return self.$dependency
    }
}
mickeysox
  • 159
  • 2
  • 14