Understanding closures

I used the following code and i have a couple of issues with it


int SomeInts = [1,2,3,4,5,6,7,8,9,10]

func reverseOrderFunc(num1:Int,num2,Int)->Bool{

if num1<num2

{

return false

}

return true

}

sort(SomeInts,reverseOrderFunc)



1.) why do we return bool

2.) xcode playground displays an error in the sort statement that it cannot invoke argument list of type ([Int],Int,Int)->Bool


Kindly help me out of this confusion


Regards,

Navjot

The code you posted isn't even correct syntax. Presumably you meant this:


let SomeInts = [1,2,3,4,5,6,7,8,9,10]
func reverseOrderFunc(num1:Int,num2:Int)->Bool{
  if num1<num2
  {
  return false
  }
  return true
}
sort(SomeInts,reverseOrderFunc)


>> 1.) why do we return bool


Because the closure you're passing to 'sort' is supposed to say whether one number comes before another: true/false. So, a Bool.


>> 2.) xcode playground displays an error in the sort statement that it cannot invoke argument list of type ([Int],Int,Int)->Bool


Because in Swift 2, 'sort' is no longer a global function, so now you invoke it like this:


SomeInts.sort (reverseOrderFunc)


Note that in this case, you can just write:


SomeInts.sort (>)


because the ">" operator provides the test you need.

>>1

So,this means that we are telling the sort function whether to swap the numbers by replying true/false to it.


>>2

Which guide should i approach to contrast the changes between swift2 and swift. I am an amature developer who read some topics of swift from version 1 and some from version2 and some are pending.


Thanks,

Navjot

1. Almost.


You are telling the sort function whether one number should come before the other number, in sort order. Whether it actually swaps the numbers at that moment, or does something more complicated, depends on what sorting algorithm it's using.


2. Because you got the error, I assumed you were using Xcode 7. If so, then you can use Edit -> Convert -> Latest Swift Syntax … to convert Swift 1 code to Swift 2.


To learn what's new, you can read the new Swift book, or you can watch the WWDC video "What's New in Swift":


https://developer.apple.com/videos/wwdc/2015/?id=106

Understanding closures
 
 
Q