0

I have a viewmodel class like so:

class SharedViewModel: ObservableObject {
    @Published var objectHeight: Int? = nil
}

and I am trying to bind to bind the variable to a textfield with a number formatter like so (the variable needs to be used throughout so in the current view the viewmodel is an @EnvironmentObject):

TextField("Height", value: $sharedViewModel.$objectHeight, formatter: NumberFormatter()

But I get this error when I hit the enter key in the simulator: Could not cast value of type '__NSCFNumber' (0x7fd9d6830fa8) to 'Combine.Published<Swift.Optional<Swift.Int>>.Publisher' (0x7fd9d5197d10).

Edit: Using an optional Int as just a state variable works fine it is the Published tag while using an Observable object as an EnvironmentObject that seems to be causing the issue. However, I need this variable inside the EnvironmentObject as it is used in multiple views.

lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
  • 1
    What if the Published Int is _not_ an Optional? – matt Jul 14 '21 at 20:59
  • Same result unfortunately, also tried using a double instead of an int I think it is to do with the Published tag but not entirely sure, as I am using a published String value in a Picker and that works fine. – Louis Davies Jul 14 '21 at 21:03

1 Answers1

0

Make it non-optional and remove the $ before $objectHeight. Only leave the ViewModel one

$sharedViewModel.objectHeight
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48