What does the underscore mean before a variable in Swiftui in an init()?

Viewed 3267

What does the underscore mean before momentDate? Why is it needed?

enter image description here

1 Answers

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).

Related