Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Function Returning Function in Swift

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 36
    Comment on it

    Hi,

     

    As we all know that Swift comes with new and variety of enhancements over objective C. Returning a function as a return type of a function is also one of them.

    Here we are defining two functions which are accepting Int kind of parameter and returning Int value.

    func increase(_ number: Int ) ->  Int{
         return number + 1
    }
            
    func decrease(_ number: Int ) ->  Int {
         return number - 1
    }


    Now we are going to create a new function having function as a return type.       

    func myFunction(shouldIncrease: Bool ) -> (Int) -> Int {
          return shouldIncrease ? increase : decrease
    }

    In this case ‘myFunction’ is accepting a parameter of Bool kind and returning a function(which is accepting a parameter of Int kind and returning Int value).

    Above function can be used as:

    let modify = myFunction(shouldIncrease: true)

    Here ‘modify’ is assigned as a function which is being returned as a value by ‘myFunction’. Now ‘modify’ will operate with one param of Int kind and will return Int value.
    example:

    let modifiedNumber = modify(20)

    That way you can use function as a return type in your program and can make your program more flexible.

     

     

    Thank you

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: