issues
search
TeamCoook
/
iOSInterviewQuestions
✅ iOS 개발자 기술 면접 대비
18
stars
0
forks
source link
[레벨 1] `10주차` 6. Swift에서 클로저(Closure)란 무엇이며, 어떻게 사용하나요?
#20
Open
longlivedrgn
opened
3 months ago
longlivedrgn
commented
3 months ago
클로저의 캡처 리스트(Capture List)는 어떤 역할을 하나요?
@escaping 클로저와 non-escaping 클로저의 차이점은 무엇인가요?
트레일링 클로저(Trailing Closure) 문법은 언제 사용하면 좋나요?
ohdair
commented
3 months ago
블로그 기재
longlivedrgn
commented
3 months ago
Swift에서 클로저(Closure)란 무엇이며, 어떻게 사용하나요?
클로져는 크게 두개로 나뉘게 된다.
익명 클로져
네임드 클로져
여기서 네임드 클로져가 우리가 쉽게 알고 있는 func가 붙은 함수이고, 익명 클로져가 우리가 흔히 말하는 익명함수 - 즉 클로져라고 불리우게 된다.
그래서 클로져는 1급 객체이다.
변수나 상수에 대입이 가능하고, 함수 return 값 혹은 함수의 파라미터 값으로 넣을 수 있다.(함수가 1급 객체이므로)
함수의 파라미터로 closure가 들어갈 경우, 만약 함수의 마지막 argument로 들어가게될 경우 Trailing closure 형식으로 변경할 수 있다. (그 외에도 경향 문법등이 존재한다.)
클로저의 캡처 리스트(Capture List)는 어떤 역할을 하나요?
클로져는 값 타입이든, 참조 타입이든 외부에 있는 변수를 참조 캡쳐를 해버린다.
따라서 값 타입의 경우 내가 복사본을 만들고 싶을 경우 캡처 리스트를 활용하면 된다.
이럴 경우, 외부에 있는 값 타입의 변수를 복사해서 클로져 안에서 활용할 수 있다.
클로져 안에서 변경을 해도, 클로져 밖에서는 변경된 사실을 모른다.
[@escaping](https://github.com/escaping)
클로저와 non-escaping 클로저의 차이점은 무엇인가요?
@escaping 클로저와 non-escaping 클로저의 차이점은 무엇인가요?
기본적으로 함수의 파라미터로 들어온 클로저는 함수의 scope이 끝나기 전에 실행이되어야한다.
따라서, 함수 안에서 변수나 상수로 할당 받을 수 없고, DispatchQueue를 활용해서 함수가 끝난 이후에 실행시킬 수도 없다.
그러나 escaping 클로져의 경우, 함수의 scope이 끝난 이후에도 해당 클로져를 실행시킬 수 있다.
상수나 변수로 할당받을 수 있다.
트레일링 클로저(Trailing Closure) 문법은 언제 사용하면 좋나요?
트레일링 클로져는 함수의 마지막 아큐먼트로 클로져가 들어왔을 때 활용할 수 있습니다.
completion handler를 트레일링 클로져 설정하면 좋을듯싶다.