
swift nested functionLanguage/Swift2022. 8. 22. 12:43
Table of Contents
swift 함수는 중첩하여서 작성을 할 수 있습니다.
함수 내 작성할 수 있는 Inner functio의 수는 제한이 없지만, 많아질수록 구조가 복잡하고 유지보수가 힘든 코드가 됩니다.
Inner function은 Outer function이 호출되었을 때, 생성되었다가 소멸됩니다( Life Cycle )
말보다는 코드로 쉽게 이해를 하는 게 좋을 거 같습니다.
// outer function
func addNumbers(_ num1: Int, _ num2: Int) {
print("Addition")
// inner function
func display(num1: Int, num2: Int) {
print("\(num1) + \(num2) =", num1 + num2)
}
// calling inner function with two values
display(num1: num1, num2: num2)
}
// calling outer function
addNumbers(5, 1)
/* resulut is
* 5 + 1 = 6
*/
위와 같이 함수 내부에서 함수를 동작하는 것인데, 내부적으로 공통적으로 쓰는 것을 함수로 만들어서 사용하면 괜찮을 거 같습니다.
또 다르게 내부 함수를 반환하기도 합니다.
func operations(param: Character) -> (Int, Int) -> Int {
func addNumbers(_ num1: Int, _ num2: Int) -> Int {
print("\(num1) + \(num2) =", num1 + num2)
return num1 + num2
}
func subNumbers(_ num1: Int, _ num2: Int) -> Int {
print("\(num1) - \(num2) =", num1 - num2)
return num1 - num2
}
return param == "+" ? addNumbers(_:_:) : subNumbers(_:_:)
}
let addOperation = operations(param: "+")
let subOperation = operations(param: "-")
var _ = addOperation(100, 1)
var _ = subOperation(1, 11)
함수를 반환 위와 같이 사용을 할 수가 있습니다.
어떻게 사용할 지는 감이 안오지만, 이렇게도 활용할 수 있다는 게 재밌는 거 같습니다
'Language > Swift' 카테고리의 다른 글
swift date, dateFormatter 날짜 구하기 (0) | 2022.08.23 |
---|---|
swift computed property 연산 프로퍼티 (0) | 2022.08.23 |
swift defer 블록 (0) | 2022.08.22 |
[Swift] continue, fallthrough-switch, where-for, enumerated, zip, indices (0) | 2022.08.07 |
[Swift] guard 문 (0) | 2022.08.07 |
@jaewpark :: 코스모스, 봄보다는 늦을지언정 가을에 피어나다
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!