What does the _
mean before momentDate
? Why is it needed?
@Binding var momentDate: Date
init(momentDate: Binding<Date>) {
UIDatePicker.appearance().backgroundColor = UIColor.white
self._momentDate = momentDate
}
The underscored variable name refers to the underlying storage for the Binding
struct. This is part of a language feature called Property Wrappers.
Given one variable declaration, @Binding var momentDate: Date
, you can access three variables:
self._momentDate
is the Binding<Date>
struct itself.self.momentDate
, equivalent to self._momentDate.wrappedValue
, is a Date
. You would use this when rendering the date in the view's body.self.$momentDate
, equivalent to self._momentDate.projectedValue
, is also the Binding<Date>
. You would pass this down to child views if they need to be able to change the date.For Binding
, the "projected value" ($
) is just self
, and the difference between _
and $
is only in the access level. However, other property wrappers may project a different type of value (see the @SmallNumber
example in the language guide).