Swift Program to Create a Nested Function With the Return Value

Swift Program to Create a Nested Function With the Return Value

Swift program to create a nested function with the return value

// Swift program to create a nested function 
// with return values

func calculate(with opr:String) -> (Int, Int) -> Int {  
    func addition(n1:Int, n2:Int) -> Int { 
        var res:Int=0
        res = n1 + n2
        return res
    }  
    func subtraction(n1:Int, n2:Int) -> Int {  
        var res:Int=0
        res = n1 - n2
        return res
    }  
    
    let fun = (opr == "+") ?  addition : subtraction  
    
    return fun  
}  

var result = 0

let AddNum = calculate(with: "+")  
result = AddNum(50, 20) 
print("Addition is: ",result) 

let SubtractNum = calculate(with: "-")  
result = SubtractNum(50, 20) 
print("Subtraction is: ",result)

output

Addition is:  70
Subtraction is:  30

...Program finished with exit code 0
Press ENTER to exit console.
Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment