Parentheses in Function and Closure - swift

I am bit confused on declaring parameter and return type in Swift.
does these parameter and return type have the same meaning? What is the use of those parentheses ()?
func myFunction() -> (()-> Int)
func myFunction() -> (Void-> Int)
func myFunction() -> Void-> Int

First... () and Void are the same thing you have two different ways of writing the same thing.
Second... The -> is right associative. So using parens as you have in your examples are meaningless, much like they are with an expression such as a + (b * c). That expression is identical to a + b * c.
Basically, the three examples in your question all define a function that takes no parameters and returns a closure that takes no parameters and returns an Int.
Some more examples to help:
func myFuncA() -> () -> Int -> String {
return { () -> Int -> String in return { (i: Int) -> String in String(i) } }
}
func myFuncB() -> () -> (Int -> String) {
return { () -> Int -> String in return { (i: Int) -> String in String(i) } }
}
func myFuncC() -> (() -> Int) -> String {
return { (f: () -> Int) in String(f()) }
}
In the above, myFuncA is identical to myFuncB, and they are both different than myFuncC.
myFuncA (and B) takes no parameters, and returns a closure. The closure it returns takes no parameters and returns another closure. This second closure takes an Int and returns a String.
myFuncC takes no parameters and returns a closure. The closure it returns takes a closure as a parameter and returns a String. The second closure takes no parameters and returns an Int.
Hopefully, writing it in Prose hasn't made it even more confusing.

Related

How can a closure in Swift only be passed in a * for the reduce function?

extension Array {
func reduce<T>(_ initial: T, combine: (T, Element) -> T) -> T {
var result = initial
for x in self {
result = combine(result, x)
}
return result
}
}
How does the below function work when it only passes a * to the combine closure?
func productUsingReduce(integers: [Int]) -> Int {
return integers.reduce(1, combine: *)
}
static func * (lhs: Self, rhs: Self) -> Self is an operator function defined on the Numeric protocol. So, you are really just passing in a function that takes two arguments.
What does the declaration mean?
combine: (T, Element) -> T
It says: the combine parameter is a function that takes two parameters, a T and an Element, and returns a T.
Well, in Swift, operators are functions, and * is such a function. So it suffices to pass a reference to this function as the combine parameter. The bare name, *, is that reference.

Why does use of closure shorthand-named variables has to be exhaustive in a singular return expression in Swift?

The following piece of code are erroneous in Swift.
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {$0}))
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {return $0}))
The error given by XCode playground is Cannot convert value of type '(Int, Int)' to closure result type 'Int'.
While the following pieces of code are completely fine.
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {$0 + $1}))
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {$1; return $0}))
func foo(closure: (Int, Int) -> Int) -> Int {
return closure(1, 2)
}
print(foo(closure: {a, b in a}))
It seems that in a situation where arguments to a closure are referred to by shorthand argument names, they must be used exhaustively if the the body of the closure only consists of the return expression. Why?
If you just use $0, the closure arguments are assumed to be a tuple instead of multiple variables $0, $1 etc. So you should be able to work around this by extracting the first value of that tuple:
print(foo(closure: {$0.0}))
Your "why" is like asking "why is an American football field 100 yards long?" It's because those are the rules. An anonymous function body that takes parameters must explicitly acknowledge all parameters. It can do this in any of three ways:
Represent them using $0, $1, ... notation.
Represent them using parameter names in an in line.
Explicitly discard them by using _ in an in line.
So, let's take a much simpler example than yours:
func f(_ ff:(Int)->(Void)) {}
As you can see, the function f takes one parameter, which is a function taking one parameter.
Well then, let's try handing some anonymous functions to f.
This is legal because we name the parameter in an in line:
f {
myParam in
}
And this is legal because we accept the parameter using $0 notation:
f {
$0
}
And this is legal because we explicitly throw away the parameter using _ in the in line:
f {
_ in
}
But this is not legal:
f {
1 // error: contextual type for closure argument list expects 1 argument,
// which cannot be implicitly ignored
}

What is the meaning of void -> (void) in Swift?

I know the meaning of (void) in objective c but I want to know what is the meaning of this code:
(Void) -> (Void)
In Swift.
() -> () just means Void -> Void - a closure that accepts no parameters and has no return value.
In Swift, Void is an typealias for an empty tuple, ().
typealias Void = ()
The empty tuple type.
This is the default return type of functions for which no explicit return type is specified.
For an example
let what1: Void->Void = {}
or
let what2: Int->Int = { i in return i }
are both valid expressions with different types. So print has the type ()->() (aka Void->Void). Strictly speaking, printThat has type (() -> ()) -> () (aka (Void->Void)->Void
Void function doesn't has a lot of sense as Int function etc ... Every function in Swift has a type, consisting of the function’s parameter types and return type.
Finally, regarding "void" functions, note that there is no difference between these two function signatures:
func myFunc(myVar: String) // implicitly returns _value_ '()' of _type_ ()
func myFunc(myVar: String) -> ()
Curiously enough, you can have an optional empty tuple type, so the function below differs from the two above:
func myFunc(myVar: String) -> ()? {
print(myVar)
return nil
}
var c = myFunc("Hello") /* side effect: prints 'Hello'
value: nil
type of c: ()? */
Same as Swift mean.No parameter no return value.

What is the syntax for a closure argument in swift

In Swift headers, the isSeparator: argument accepts a closure
public func split(maxSplit: Int = default, allowEmptySlices: Bool = default, #noescape isSeparator: (Self.Generator.Element) throws -> Bool) rethrows -> [Self.SubSequence]
But in the documentation, it lists closure syntax differently
{ (parameters) -> return type in
statements
}
How are you supposed to know that (Self.Generator.Element) throws -> Bool rethrows refers to a closure / requires a closure? Are there other ways that the headers/docs might list argument as meaning a closure?
The "thing" giving away that this is a closure is the ->. The full type is
(Self.Generator.Element) throws -> Bool
It means that the closure takes a variable of type Self.Generator.Element and has to return a Bool upon some calculation based on the input. It may additionally throw some error while doing so - that is what the throws is for.
What you then write
{ (parameters) -> return type in
statements
}
would be an actual implementation, a value of some generic closure type.
The type of a closure is for example (someInt:Int, someDouble:Double) -> String:
var a : ((someInt:Int, someDouble:Double) -> String)
Once again the thing giving away that a is actually a closure is the -> in the type declaration.
Then you assign something to a via some code snippet following your second code block:
a = { (integer, floating) -> String in
return "\(integer) \(floating)"
}
You can tell by the argument's type. Everything in Swift has a type, including functions and closures.
For example, this function...
func add(a: Int, to b: Int) -> Int { return a + b }
...has type (Int, Int) -> Int. (It takes two Ints as parameters, and returns an Int.)
And this closure...
let identity: Int -> Int = { $0 }
...has type Int -> Int.
Every function and closure has a type, and in the type signature there is always a -> that separates the parameters from the return value. So anytime you see a parameter (like isSeparator) that has a -> in it, you know that the parameter expects a closure.
the isSeparator definition means (Self.Generator.Element) throws -> Bool that you will be given an Element and you should return a Bool. When you will call split, you then can do the following :
[1,2,3].split(…, isSeparator : { element -> Bool in
return false
})
This is a pure silly example but that illustrates the second part of your question

“Functions are a first-class type” in swift?

the little knowledge , I have about first class function is that it supports passing functions as arguments and we can also return them as the values in another function ... I am very new in Swift programming language can anyone please elaborate it with an example.
A very simple example to demonstrate this behaviour:
func functionA() {
println("Hello by functionA")
}
func executeFunction(function: () -> ()) {
function()
}
executeFunction(functionA)
First-Class functions are functions that can return another functions.
For instance:
func operate( operand: String) -> ((Double, Double) -> Double)?{
func add(a: Double, b: Double) -> Double {
return a + b
}
func min(a: Double, b: Double) -> Double{
return a - b
}
func multi(a: Double, b: Double) -> Double {
return a * b
}
func div (a: Double, b: Double) -> Double{
return a / b
}
switch operand{
case "+":
return add
case "-":
return min
case "*":
return multi
case "/":
return div
default:
return nil
}
}
The function operate returns a function that takes two double as its arguments and returns one double.
The usage of this function is:
var function = operate("+")
print(" 3 + 4 = \(function!(3,4))")
function = operate("-")
print(" 3 - 4 = \(function!(3,4))")
function = operate("*")
print(" 3 * 4 = \(function!(3,4))")
function = operate("/")
print(" 3 / 4 = \(function!(3,4))")
When you don't care about the implementation of a function, using First-Class functions to return these functions become beneficials. Plus, sometimes, you are not responsible to develop (or not authorised ) of the functions like add, min. So someone would develop a First-Class function to you that returns these functions and it is your responsibility to continue ....
A function that returns a function while capturing a value from the lexical environment:
A function of an array of Comparables that returns a function of a test predicate that returns a function of a value that returns a Bool if the value is the extreme of the array under test. (Currying)
Any programming language is said to have first-class-functions, when functions are treated like normal variables. That means a function can be passed as parameter to any other function, can be returned by any function and also can be assigned to any variable.
i.e., (Referring apple's examples)
Passing function as parameter
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
Returning function
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
Properties of First class function
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to
another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, …
refer https://www.geeksforgeeks.org/first-class-functions-python/