I was going through Apple's introduction to Swift and came across such example:
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
Can you please explain the syntax of the return type of the makeIncrementer function? I understand that this function returns another function, but there role of ((Int) -> Int)
in this context is still unclear for me.
In Swift, there are two kinds of types: named types and compound types. A named type is a type that can be given a particular name when it's defined. Named types include classes, structures, enumerations, and protocols.
Swift provides an additional integer type, Int , which has the same size as the current platform's native word size: On a 32-bit platform, Int is the same size as Int32 . On a 64-bit platform, Int is the same size as Int64 .
In Swift, the underscore operator (_) represents an unnamed parameter/label. In for loops, using the underscore looping parameter is practical if you do not need the looping parameter in the loop.
In Swift, variadic parameters are the special type of parameters available in the function. It is used to accept zero or more values of the same type in the function. It is also used when the input value of the parameter is varied at the time when the function is called.
It indicates that the function returns a function and that returned function takes an Int
as an input parameter and returns an Int
as well.
Defining functions within functions is perfectly legal in Swift.
(Int -> Int)
denotes a closure (or function) taking an Int
as parameter and returning an Int
.
The syntax for declaring a closure type is:
(parameters) -> (return_types)
parameters
is a list of parameters the closure receives as input, and return_types
is the list of values the closure returns. Both are tuples, but in case of one parameter or one return type, the parenthesis identifying the tuple can be omitted. So for example a clousure expecting one parameter and returning one value can be defined as:
parameter -> return_type
In your case:
Int -> Int
is a closure having 1 input parameter of Int
type and returning a Int
The return type is enclosed in parenthesis to make it clear that's the return type, but you could also write it as:
func makeIncrementer() -> Int -> Int {
Which is in my opinion less readable than
func makeIncrementer() -> (Int -> Int) {
I am not exactly familiar with the syntax of swift, but I guess all higher-order functions work the same. makeIncrementer
is a function that:
Int
parameterInt
Visual explanation (a -> b
means a function that takes type a
as the parameter and returns type b
):
makeIncrementer -> (Int -> Int) ^ | | a function that takes an Int and returns an Int, i.e. (addOne in your case)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With