-
Notifications
You must be signed in to change notification settings - Fork 0
[LEVEL 1] 04 - Closure #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
LEVEL 1/04-Closure.md
Outdated
| @@ -0,0 +1,20 @@ | |||
| ## 04. Closure | |||
| ### Swift에서 클로저(Closure)란 무엇이며, 어떻게 사용하나요? | |||
| - Swift에서 클로저는 이름 없는 함수입니다. | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
클로저 공식 문서에 보면 다른 프로그래밍 언어의 익명 함수와 닮았다고 되어 있지만 그 밑의 설명을 보면 함수를 closures that have a name 라고 표현합니다. 때문에 클로저가 함수를 포함하는 형식이 되기에 클로저는 그룹 코드인데 표현 중에 이름 있는 클로저는 함수라고 부르고 이름 없는 클로저는 이를 제외한 것이라고 보는 것은 어떨까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
그 시각이 좀 더 타당하다고 생각되네요! 반영하여 수정하도록 하겠습니다~!
| ### @escaping 클로저와 non-escaping 클로저의 차이점은 무엇인가요? | ||
| - 클로저가 함수의 매개변수로 전달되었지만, 함수 반환 이후에 호출되는 경우 클로저가 탈출(escaping)한다고 할 수 있습니다. | ||
| - 이 때 매개변수에 @escaping을 작성해 해당 클로저는 탈출이 허용됨을 나타낼 수 있습니다. | ||
| - 만약 탈출 클로저 내부에서 클래스 인스턴스 self를 참조하게 된다면, 두 참조 타입이 서로를 참조하는 순환 참조가 발생하게 됩니다. | ||
| - 이를 방지하기 위해 캡처 리스트에서 weak 또는 unowned 키워드를 사용해 레퍼런스 카운트를 증가시키지 않도록 방지해야 합니다. | ||
| - 클로저의 생명주기가 self보다 긴 경우를 대비하기 위해 weak 키워드를 사용해주는 것이 좋습니다. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
구조체와 열거형에서도 escaping closure를 사용할 수 있나요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
구조체의 경우 아래와 같이 사용할 수 있음을 확인했습니다!
struct Foo {
let bar: () -> Void
init(bar: @escaping () -> Void) {
self.bar = bar
}
}
let foo = Foo(bar: {
print("Hello World!")
})
foo.bar()열거형의 경우 연관값으로 클로저를 전달할 경우 escaping 함수로 동작한다는 글을 확인했습니다~!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
mutating 키워드가 붙은 함수에서도 escaping closure를 사용할 수 있을까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
코드로 테스트해 봤을 때에는 함수에서 인자로 escaping 클로저를 받는 경우, 함수 내부에서 구조체 프로퍼티로 선언된 클로저를 사용하는 경우 둘 다 사용 가능했습니다~!
혹시 제가 놓치고 있는게 뭘까요?!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
아하 그렇다면 해당 클로저 내부에서 self 키워드 사용해보셨나요?!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
헉 탈출 클로저 내부에서 값 타입 self에 접근하는 케이스를 놓치고 있었네요~!
바보같이 클로저 사용 가능 여부만 체크하고 있었습니다 ㅠㅠ
알려주셔서 감사합니다~!
값 타입은 immutable 하기 때문에, 기본적으로 escaping 클로저 내부에서 self 값에 대한 변경이 불가능하겠군요.
self를 변경 가능하도록 mutating 키워드를 붙여도 나중에 실행될 수 있는 escaping 클로저 특성상 메모리 접근 충돌 문제가 발생 가능합니다.
이를 방지하기 위해 컴파일 에러가 발생하고, 이를 해결하기 위해서는 캡처 리스트를 사용해 값의 복사본을 사용해야 한다는 것 까지 알게 되었습니다~!
값 타입을 self로 캡처할 때 고려해야 할 부분들이 여럿 있군요... 감사합니다 민송님!
내용 확인하신 후 반영하도록 하겠습니다~!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
네 맞습니다! 관련된 이야기를 하고 싶었습니다 ㅋㅋㅋ
|
@mint3382 |
아 세상에 제가 찾아보고 수정해놓겠습니다... |
| ### @escaping 클로저와 non-escaping 클로저의 차이점은 무엇인가요? | ||
| - 클로저가 함수의 매개변수로 전달되었지만, 함수 반환 이후에 호출되는 경우 클로저가 탈출(escaping)한다고 할 수 있습니다. | ||
| - 이 때 매개변수에 @escaping을 작성해 해당 클로저는 탈출이 허용됨을 나타낼 수 있습니다. | ||
| - 만약 탈출 클로저 내부에서 클래스 인스턴스 self를 참조하게 된다면, 두 참조 타입이 서로를 참조하는 순환 참조가 발생하게 됩니다. | ||
| - 이를 방지하기 위해 캡처 리스트에서 weak 또는 unowned 키워드를 사용해 레퍼런스 카운트를 증가시키지 않도록 방지해야 합니다. | ||
| - 클로저의 생명주기가 self보다 긴 경우를 대비하기 위해 weak 키워드를 사용해주는 것이 좋습니다. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
네 맞습니다! 관련된 이야기를 하고 싶었습니다 ㅋㅋㅋ
NeoSelf1
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
오,,, self의 타입 간 escaping 클로저가 동작하는 매커니즘에 대해 얕게나마 이해한것같습니다... 최고입니다 다들
issue #4
04. Closure
Swift에서 클로저(Closure)란 무엇이며, 어떻게 사용하나요?
클로저의 캡처(Capture) 기능은 무엇인가요?
@escaping 클로저와 non-escaping 클로저의 차이점은 무엇인가요?
트레일링 클로저(Trailing Closure) 문법은 어떤 경우에 유용한가요?