What does the underscore mean before momentDate? Why is it needed?
The underscore refers to the property wrapper itself. score refers to the value inside the property wrapper. _score refers to the property wrapper. $score refers to the property wrapper's projected value; in the case of @State , that is a Binding .
In Swift, the underscore operator (_) represents an unnamed parameter/label. In for loops, using the underscore looping parameter is practical if you do not need the looping parameter in the loop.
An underscore in front usually indicates an instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things. Follow this answer to receive notifications.
There are a few nuances to different use cases, but generally an underscore means "ignore this". When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With