Higher order functions in Swift 3#1

http://streetwill.co/posts/594-road-life

Recently i read more thing about Functional programming(FP). I got a basic knowledge of Swift programming. I learn Functional programming because i want to know What is functional programming ?, Why it matters ?, How we use in the mobile develop ? That why i research about it.

Basically you have to kinda change your perspective when your learn new programming paradigm. It make me dizzy in sometime but it worth after your learn about it.

But this article i don’t want to explain about What is FP ? Why use FP ?.
I can’t told you what is more advanced concepts such as Functors, Applicative functors, and Monads in FP.

OHHHH

In some part of Swift I’ve learned the basics about Higher-order functions and i want to expand my knowledge in this way.

What is Higher-order functions in Swift way ?

Yeh What is ? … In definitions

Higher-order functions is Functions that can accept other functions as parameters.

Before we drive into a details we should learn useful higher-order function that Swift provides for us.

So I just create simple example of higher-order function with

class Student {
var name: String
var age: Int

init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let anak = Student(name: “Anak”, age: 30)
let peter = Student(name: “Peter”, age: 31)
let steven = Student(name: “Steven”, age: 25)
let susan = Student(name: “Susan”, age: 20)
let ethan = Student(name: "Ethan", age: 28)
let students = [anak, peter, steven, susan, ethan]

I create students array as constants because in functional programming it recommended to define properties as immutable as much as possible.

So we will start with simple Higher-order function

Higher-order function

func concat(text: String, withString b: String) -> String {
return text + “ “ + b
}
typealias ConcatTextWithString = (String, String) -> String
func higherConcat(number: Int, withString b: String, withFunc: ConcatTextWithString) -> String {
return “\(number) “ + withFunc(“Hello”, b)
}
let justConcat = concat(text: “Hello”, withString: “Anak”)
let finalString = higherConcat(number: 5, withString: “Anak”, withFunc: concat)

In this example this higherConcat function is higher-order function, it take one other functions as parameter and use it in closure. For higherConcat it receive 3 parameter 2 is Int and String and last one is Function. That make higherConcat is higher-order function.

Function in Swift 3 is very powerful, function can return type, value, and return function by function. We can write flexible function by higher-order function.

Swift has build in higher-order function such as map, filter, reduce also we can write a flexible own higher-order functions.

Let’s continue to . . .


Map

Map map map … Map is a function of transforming the elements of an array using a function. We can use map with collections type such as array. We use map to solve for-in loops to go through the collection and transform each element in the array.

When you want to transform … just call Map

The following example gives two different approaches to array element of students age.

// func map<U>(transform: (T) -> U) -> [U]
// Imperative way
var studentsAgeArray:[Int] = []
for student in students {
studentsAgeArray.append(student.age)
}
print(studentsAgeArray)
// Declarative way
// short-hand syntax $0 is Student
let studentsAge = students.map({ $0.age })
print(studentsAge)
// long form syntax
let newStudentsAge = students.map { (student: Student) -> Int in
return student.age
}
print(newStudentsAge)

In Imperative way we create studentsAgeArray properties for store age of student and use for-in loops to put age into it. It required us to create studentsAgeArray mutated repeatedly while the task is performed in the loop. But in map function we can clearly declare the transformation and make our code simpler and shorter in one line.

Map function can be applied to more use-case. This example show how to transform array of Student to array of Age(Int) by map function.

Type of result or map operations is not limited. You can transform [Student] to [String] or [Int] to [String] or [Any] to [Any]. Like example below

let celsius = [45, 50, 34, 43, 42].map { (fahrenheit) -> Int in
return Int(5.0 / 9.0 * (Double(fahrenheit) — 32.0))
}
let studentsDict = students.map { (student) -> [String: Int] in
return [student.name: student.age]
}

Now you can try on map function in playground. Maybe transform type, multiplier, increase, or whatever what you want, map is very flexible, powerful and make your function usable and more understandable.

Don’t believe me . . . trying by your self

That’s it for today for Higher-order function in Swift 3.

See you guys next time with filter and reduce and more custom own higher-order function.

You can leave your comment below. Let’s share idea! Bye bye ❤

Read next article about Higher-order function 
- https://medium.com/@igroomgrim/higher-order-functions-in-swift-3-2-a8445de53088#.mgzvr8uhm