1

I post a question about closure but it was kept as on hold When to use closures in swift?

Now i want to go in detail and being more specific. How does this line work?

    let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
    func backwards(s1: String, s2: String) -> Bool {
        return s1 > s2
    }
   var reversed = sorted(names, backwards)

When I pass a function as an argument.How does this takes value from the names array?

Community
  • 1
  • 1
  • There is documentation on Swift closures provided by Apple, you need to study it. – zaph Apr 24 '15 at 05:06
  • 2
    It looks like you're getting this from the Swift closure documentation. I would look into the `sorted(_:_:)` function from the Swift standard library documented [here](https://developer.apple.com/library/ios/documentation/General/Reference/SwiftStandardLibraryReference/Algorithms.html#//apple_ref/doc/uid/TP40014608-CH15-DontLinkElementID_1) to see how it sorts sequences in combination with a closure. – Aaron Apr 24 '15 at 05:20
  • There is no closure that is capturing any values here – newacct Apr 24 '15 at 23:00
  • @newacct perhaps if i pass the function in the sorted method then...?? –  Apr 25 '15 at 01:35
  • @copeME: I don't understand what you are saying. You have a function, `backwards`. It doesn't capture any variables (the only variables used in the function, `s1` and `s2`, are parameters; "captured" variables mean variables that are used in the function but declared outside the function). – newacct Apr 25 '15 at 21:04

2 Answers2

0

You should look at the documentation, but here is an example sorting function (selection sort because that is the simplest):

func selectionSort<T>(inout array: [T], comparator: (T,T) -> Bool) {
    var min: Int

    for n in 0..<array.count {
        min = n

        for x in (n + 1)..<array.count {
            if comparator(array[x], array[min]) {
                min = x
            }
        }

        if min != n {
            let temp = array[min]
            array[min] = array[n]
            array[n] = temp
        }
    }
}

selectionSort(&names, backwards)

As you can see the function uses the closure to check for order, the exact number of times your closure gets called depends on the implementation of the sorted function's implementation.

vrwim
  • 13,020
  • 13
  • 63
  • 118
  • @copeME if I answered your question, don't forget to accept it. If you are happy with my answer, you can also upvote it. – vrwim Apr 29 '15 at 13:16
  • @copeME I hope you will be safe. Thanks for the upvote! – vrwim Apr 30 '15 at 16:47
-8

Most of the Java script Developer stuck in closure even they use closure in multiple places. There are many blogs to explain Closure. I came across most of the blogs and decided to make it more simple as I can. In a very simple way I can say Closure is a function which has the memory of Variables in which it was defined.

Ex.1:

function increment(i){  
    return function(){
        return i++;
    }
}

var increase_1 = increment(5); //passing a reference or scope variable 5

//increase_1 store value of i as 5 in memory
increase_1()                            //5
increase_1()                            //6
increase_1()  

                      //7

Let's have another simple example Ex.2:

add(3,5);
add(3)(5);

Now I need a function that can execute both expression....

function add(a,b){
  if(arguments.length===2){
    return a+b;
  } else {
   return function(b){
      return a+b;
    }    
  }
}

Ex:3:

// A typical example
function addLinks () {
    for (var i=0, link; i<5; i++) {        
        link = document.createElement("a");
        link.innerHTML = "Link " + i;     
        link.onclick = function(){
         console.log(i);
        }
        document.body.appendChild(link);
    };   
}
addLinks();

//What will be the output of this. When you execute this it create a link, and on click it will print some value. So what would be the value it print on click of link1. Think about it for a while..... I know, initially you get confused. yes it prints 5. Not only click on this particular link but on each link, it gives you 5. So, now I want to print 0,1,2,3,4. Yes that's right when I click on link0, it prints 0, on link1, it prints 1 and so on.. Now, I want to you check the example 1 closely and try to implement in the same way and try to memorise some thing self executing annonmys function.

function addLinks () {
    for (var i=0, link; i<5; i++) {        
        link = document.createElement("a");
        link.innerHTML = "Link " + i;     
        link.onclick = function(c){
          return function(){
            console.log(c);
          }
        }(i);//passing a reference 
        document.body.appendChild(link);
    };   
}

addLinks();

So, if you see this example closely, when an event handler is being bind with the link, a reference or scope is passed. This is the same way, in which jQuery was implemented.

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
Harendra
  • 1
  • 4