macOS, iOS

[Combine] Combine에서 _(underscore)의 의미는 무엇일까?

SweetDev 2021. 3. 8. 12:36

stackoverflow.com/questions/65209314/what-does-the-underscore-mean-before-a-variable-in-swiftui-in-an-init

 

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

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

stackoverflow.com

변수이름 앞에 언더바를 붙이는 코딩스타일은 스위프트에서는 지양해오던 바 였다.

(Property Wrapper내부에서 사용하던 코딩 스타일이었다.!! 일반 변수에서 사용하는걸 지양했다는 뜻이다.)

 

 

그러나, Combine에서 Binding변수 자체에 접근하기 위해서 사용된다. 

 

 

 

예를 들어,

@Binding var momentDate: Date

 라는 변수가 있다고 하면, 

 

다음과 같이 세가지 방법으로 접근할 수 있다. 

 

1. 

self._momentDate

Binding<Date> 

struct 그 자체

 

2. 

self.momentDate

Date

self._momentDate.wrappedValue와 같음

주로 view의 body에서 date를 쓸 때 갖다 쓴다. 

 

3. 

self.$momentDate

Binding<Date>

self._momentDate.projectedValue와 같음

child view에서 변수에 접근해서, date의 값을 바꿔야 할 때 전달해주는 형태