Global function (vs) Enclosing function

 n Swift, a global function is a function that is defined outside of any class or structure and is available throughout the entire program. On the other hand, an enclosing function is a function that is defined within another function, and can only be accessed within the scope of the enclosing function. 

Here's an example of a global function in Swift:

func greet(name: String) {
    print("Hello, \(name)!")
}

This function can be called from anywhere in the program, like this:

greet(name: "John") // prints "Hello, John!"

And here's an example of an enclosing function:

func outerFunction() {
    func innerFunction() {
        print("This is the inner function.")
    }
    
    print("This is the outer function.")
    innerFunction()
}

outerFunction() // prints "This is the outer function."
 followed by "This is the inner function."

In this example, the innerFunction is defined inside the outerFunction, and can only be called from within the outerFunction. When outerFunction is called, it prints "This is the outer function." and then calls innerFunction, which prints "This is the inner function."


Comments

Popular Posts