2. 함수의 합성, Composition (Functional Programming in Swift)

합성(Composition)에 관해 알아보도록 하겠습니다.

jinShine
jinshine 기술 블로그
2 min readMay 1, 2019

--

이전 글 순수함수(Pure Function), Functional Programming in Swift

함수가 합성되기 위해서는 함수의 반환값과 반환값을 파라미터(Input)으로 받아들이는 값은 타입이 서로 같아야 합니다.

음.. 당연하죠?

이해를 돕기 위한 간단한 예제

func testFunc(_ num: Int) -> Int {
return num + 50
}
func testFunc2(_ num: Int) -> String {
return "\\(num)"
}
let result = testFunc2(testFunc(100))// 150

testFunc의 함수가 Int를 입력 받아 Int를 리턴하고있고, 그 결과값이 testFunc2의 Int로 입력 받아서 사용되고있어 합성되었다고 볼 수 있죠

testFunc 리턴값이 testFunc2의 파라미터 타입이 같기때문에 가능한겁니다!

위의 예제를 좀 더 진화시켜 testFunc, testFunc2를 합성해서 합성된 함수를 한번에 사용하고있는 testFunc3이라는 함수도 만들 수 있습니다.

func testFunc(_ num: Int) -> Int {
return num + 50
}
func testFunc2(_ num: Int) -> String {
return "\\(num)"
}
func testFunc3(_ input1: @escaping (Int) -> Int, _ input2: @escaping (Int) -> String) -> (Int) -> String {
return { num in
return input2(input1(num))
}
}
let result = testFunc3(testFunc(_:), testFunc2(_:))
result(30)
// "80"

--

--