본문 바로가기
Smart Device/Swift

Swift 함수 #3 - nested functions(중첩함수)

by 언덕너머에 2014. 6. 9.

nested functions(중첩함수)

  중첩함수는 외부함수에서 선언된 변수에 접근할 수 있다.

  함수가 길거나 복잡할 경우 사용할 수 있다.

  예1)

  func returnFifteen() -> Int {

      var y = 10

      func add() {

          y += 5

      }

      add()

      return y

  }

  returnFifteen()


참고 : Apple Inc. ‘The Swift Programming Language.'


예2)

func chooseFunction(operation: Bool) -> (Int) -> Int {

    func increaseOne(input: Int) -> Int {

        return input + 1

    }

    

    func decreaseOne(input: Int) -> Int {

        return input - 1

    }

    

    return operation ? decreaseOne : increaseOne

}


var currentValue = 20

var myValue = chooseFunction(currentValue > 0)

println("Counting to zero:")

while currentValue != 0 {

    println("\(currentValue)...")

    currentValue = myValue(currentValue)

}

//-->결과

Counting to zero:

19

18

17

16

15

14

13

12

11

10

9

8

7

6

5

4

3

2

1

0