클로저 축약형 예제

w0308h 2월 15일 AM 10:39 3 0
w0308h Profile Image Level 9
2 #TIL

클로저의 여러 가지 표현 방법 - 축약형 예제

let multiply = {(value1: Int, value2: Int) -> Int in
		return value1 * value2
}

let add = {(value1: Int, value2: Int) -> Int in
		return value1 + value2
}

let result = add(10, 20)
print(result) //30
func math(x: Int, y: Int, calculate: (Int, Int) -> Int) -> Int{
		return calculate(x, y)
}

result = math(x: 10, y: 20, calculate: add) //30
result = math(x: 10, y: 20, calculate: multiply) //200
result = math(x: 10, y: 20, cal: {(value1: Int, value2: Int) -> Int in
		return value1 + value2
}) //30
result = math(x: 10, y: 20) { (value1: Int, value2: Int) -> Int in
		return value1 + value2
} //30
result = math(x: 10, y: 20, cal: {(value1: Int, value2: Int) in
		return value1 + value2
}
result = math(x: 10, y: 20) { (value1: Int, value2: Int) in
		return value1 + value2
}
result = math(x: 10, y: 20, cal: {
		return $0 + $1
}) //매개변수 생략, 단축인자(shorthand argument name) 사용
result = math(x: 10, y: 20) {
		return $0 + $1
} //trailing closure, 매개변수 생략, 단축인자 사용
result = math(x: 10, y: 20, cal: {
		$0 + $1
}) //클로저에 리턴값이 있으면 마지막 줄을 리턴하므로 return 키워드 생략
result = math(x: 10, y: 20){ $0 + $1 } //trailing closure, return 생략
댓글