36

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 } 
0

2 Answers 2

110

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

Sign up to request clarification or add additional context in comments.

3 Comments

This comment is very helpful but I cannot find an explanation specifically mentioning the underscore syntax (e.g. _somePropery) anywhere in the documentation. Your note "self._momentDate is the Binding<Date> struct itself." is the only information I can find on this. I am curious how this works internally. Is the underscore the only syntax available ? nothing similar to someProperty.wrapperItself ?
The underscores are mentioned (albeit a bit indirectly) in this documentation: docs.swift.org/swift-book/LanguageGuide/Properties.html#ID617
This answer is not helpful, so I'm not sure why the other comments say as much. Without a deep understanding of the concepts, this solution speaks at a level which is inaccessible to the reader. It's circular because you need to already know what is going on to understand the answer.
3

Official Docs

A Binding is one of various Property Wrappers.

When you use a @PropertyWrapper on a var, it synthesizes convenience code.

That includes automatically creating a private var named _yourPropVar, whose type is YourPropertyWrapper (e.g. Binding).

When you prefix that with underscore, you're referencing the synthesized private variable - the Property Wrapper itself.

When you reference yourPropVar instead, without the underscore, it's accessing the synthesized wrapped value getter instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.