Thursday 17 December 2015

Recursive Closures in Swift

Here we are going to see examples of writing Recursive Closures.

1. Write a function, that will run a given closure for a given number of times

Solution:

    func repeatTasks(times: Int, task:()->Void)
    {
        for _ in 0..<times {
            task()
        }
    }


Calling the method:
    
      repeatTasks(10) { () -> Void in
            
            print("swift is great")
        }

2. Write a function that you can reuse to create different mathematical sums

Solution:

   func mathSum(times:Int, operation:(Int)->Int)->Int
    {
        var result = 1
        for i in 1...times{
            result+=operation(i);
            print("result==\(result)")
        }
        return result;
    }

Calling the method:

  mathSum(10) { (number ) -> Int in
            number * number;
        }


Writing the Same Math Sum using fibonacci series

Solution:

   func fibonacci(number: Int) -> Int {
        if number <= 0 {
            return 0
        }
        
        if number == 1 || number == 2 {
            return 1
        }
        
        return fibonacci(number - 1) + fibonacci(number - 2)
    }

Calling the method:

    mathSum(10) { (number) -> Int in
            self.fibonacci(number);
        }

No comments:

Post a Comment