Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

swiftui

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

enter image description here

like image 646
Nighthawk Avatar asked Dec 09 '20 01:12

Nighthawk


People also ask

What is underscore in Swiftui?

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 .

What does an underscore before a variable mean Swift?

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.

What does an underscore before a variable mean?

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.

What do underscores mean in Swift?

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.


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

like image 150
jtbandes Avatar answered Sep 21 '22 11:09

jtbandes