Reputation: 2523
I'm currently working my way through the Swift Programming Manual from Apple and came across function types as parameter types.
In usual way,
func add(one : Int , _ two:Int) ->Int
{
return one+two
}
func multiply(one : Int ,_ two : Int) ->Int
{
return one*two
}
func subtract(one : Int , _ two :Int) ->Int
{
return one-two
}
add(1, 2)
subtract( 1 , 2)
multiply(1 , 2)
Using Function types as parameters,
func add(one : Int , _ two:Int) ->Int
{
return one+two
}
func multiply(one : Int ,_ two : Int) ->Int
{
return one*two
}
func subtract(one : Int , _ two :Int) ->Int
{
return one-two
}
func basic(result : (Int , Int) ->Int,_ one : Int , _ two : Int)
{
result(one,two)
}
basic(add, 1, 2)
basic(multiply, 2, 3)
So, from above code it is clear that we are writing extra function basic()
and extra lines of code which are not that useful in this example and makes it complicated.It's better not to use function types as parameter types.
So,is there any example which takes advantage of the feature?
Upvotes: 0
Views: 227
Reputation: 13243
If you look at Swift's standard library you will see that many methods do that like map
which is defined on Array
.
map
takes a function which transforms the elements of the array to a new array with a new type.
It is also a generic function but in order to keep it simple I use a function which maps Int
Arrays:
func map(_ array: [Int], _ transform: Int -> Int) -> [Int] {
var result = [Int]()
for element in array {
result.append(transform(element))
}
return result
}
// map can be used with other functions
// and also closures which are functions
// without a name and can be created "on the fly"
func addByOne(i: Int) -> Int {
return i + 1
}
func square(i: Int) -> Int {
return i * i
}
map([1,2,3], addByOne) // [2,3,4]
map([1,2,3], square) // [1,4,9]
// and so on...
// with closures
map([1,2,3]) { $0 + 1 } // [2,3,4]
map([1,2,3]) { $0 * $0 } // [1,4,9]
So it is mainly used in libraries where you can offer APIs which have a much broader range of usage.
Upvotes: 1