클로저

익명함수

일반적으로 클로저라고 하면 익명함수(unnamed-closure)를 의미하며, 클로저의 표현식은 다음과 같다.

{ (매개변수) -> 리턴타입 in
	실행구문
}

일급객체

전달 인자로 보낼 수도 있고, 변수나 상수 등으로 저장하여 전달할 수도 있으며, 함수의 반환 값이 될 수도 있는 객체를 일급객체라고 한다. 클로저는 일급객체이다.

클로저는 상수에 저장할 수 있다

let hello = { () -> () in
	print("hello")
}

let hello2 = { (name: String) -> String in
	return "Hello, \(name)"
}

hello();
// "hello"

hello2("Gunter")
// "Hello, Gunter"

hello2(name: "Gunter")
// Extraneous argument label 'name:' in call

클로저는 함수의 파라미터로 전달할 수 있다

func doSomething(closure: () -> ()) {
	closure()
}

doSomething(closure: {() -> () in
	print("hello")
})
// "hello"

클로저는 함수의 반환타입으로 전달할 수 있다

func doSomething2() -> () -> () {
	return {() -> () in
		print("hello4")
	}
}

doSomething2()()
// "hello4"

후행 클로저

클로저를 쓸 때 두번째 소괄호와 in 키워드를 생략하는 것도 가능하다.

func doSomething(closure: () -> ()) {
	closure()
})

doSomething() {
	print("hello2")
}
// "hello2"

doSomething {
	print("hello2")
}
// "hello2"

다중 후행 클로저 상황이라면, 아래의 코드와 같은 자동완성이 지원된다.

func doSomething2(success: () -> (),fail: () -> ()) {
	
}

doSomething2 {
	code
} fail: {
	code
}

클로저의 여러 모습

func doSomething3(closure: (Int,Int,Int) -> Int) {
	closure(1,2,3)
}

doSomething3(closure: {(a,b,c) in
	return a + b + c
})

doSomething3(closure: {
	return $0 + $1 + $2
})

doSomething3(closure: {
	$0 + $1 + $2
})

doSomething3() {
	$0 + $1 + $2
}

doSomething3 {
	$0 + $1 + $2
}
profile
전직 시스템엔지니어, 현직 데이터엔지니어, 하지만 하고 싶은건 iOS 개발

0개의 댓글