← back to the blog


Closures JavaScript vs Swift

Posted on January 12th, 2020 in JavaScript by George

 

Swift 

Let's start with the definition of closure as per Swift documentation:

Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

Based on the statement above let's write an example to demonstrate it in code:

 

//Swift 5.1



//Initiate provideIncrementFunc
// has an integer as parameter labeled incrementMe

func provideIncrementFunc(incrementMe amount: Int) -> () -> Int {
    // Variable to close over
    var total = 0;
    
    func increment()-> Int {
        total += amount
        return total;
    }
    
    //return function with closures
    return increment;
}


//Test with a constant let (not like JavaScript let, there you have const)
//Let in JavaScript has a different purpose, defining block-scoped variables

let incrementByFive = provideIncrementFunc(incrementMe: 5)

incrementByFive()
incrementByFive()
incrementByFive()

//Total is 15

 

Now let's recreate this in JavaScript 

 

//JavaScript


const provideIncrementFunc = (amount) => {
  
  let total = 0;
  
  //increment function is closing over the outer scoped variable total 
  //We know that let defines block-scoped variables

  const increment = () => {
    total += amount;
    return total;
  }
  
  //return function as a value, notice that we are not calling the function here yet
  return increment;
}

let incrementByFive = provideIncrementFunc(5)

incrementByFive()
incrementByFive()
//wrap in console.log the final call of incrementByFive to observer the value of total in console
console.log(incrementByFive());

 

Just to make it clear, Swift is not the same or like JavaScript. 

Swift, it is a static typed multi-paradigm, object-orientated language, JavaScript is object-orientated prototype-based language (despite the syntactic sugar added with ES6 class, constructor, etc) 

Whenever you get to use one of the main frameworks abstracted on top of each of these two programming languages you will feel the difference.

They have a very different history and different purposes (of course there are some middle grounds, as a matter of perspective).

Both languages are borrowing syntax and programing methodologies from other programming languages. And that is a good thing.

This is not the topic of this post though.

Thank you!