Search This Blog

Wednesday, October 4, 2017

Higher-order Functions in Swift


What are Higher Order Functions?


Higher-order functions are functions that can take other functions as parameters, return another function or both. Also we can pass higher-order function as parameter.


Map


Passes through the collection and performs the same operation on each element.
let array = [1, 2, 3, 4, 5]

// standard manner

var resultArray = [Int]()
for number in array {
    resultArray.append(number * number)
}
// resultArray = [1, 4, 9, 16, 25]

// manner 1
resultArray = array.map( { (value: Int) -> Int in
    return value * value
})
// resultArray = [1, 4, 9, 16, 25]

// manner 2
resultArray = array.map( { (value: Int) in
    return value * value
})
// resultArray = [1, 4, 9, 16, 25]

// manner 3
resultArray = array.map( { value in
    return value * value
})
// resultArray = [1, 4, 9, 16, 25]

// manner 4
resultArray = array.map( { value in
    value * value
})
// resultArray = [1, 4, 9, 16, 25]

// manner 5
resultArray = array.map( { $0 * $0 })
// resultArray = [1, 4, 9, 16, 25]

// manner 6
resultArray = array.map { $0 * $0 }
// resultArray = [1, 4, 9, 16, 25]

// length comparison

array.map( { (value: Int) -> Int in return value * value } )
array.map( { (value: Int) in return value * value } )
array.map( { value in return value * value } )
array.map( { value in value * value } )
array.map( { $0 * $0 })
array.map { $0 * $0 }

// working with array of objects

class Car {
    var name: String!
    var price: Int!
    init(name: String, price: Int) {
        self.name = name
        self.price = price
    }
}

let car1 = Car(name: "Toyota", price: 35000)
let car2 = Car(name: "Nissan", price: 25000)
let car3 = Car(name: "Subaru", price: 47000)
let car4 = Car(name: "Honda", price: 27999)
let carsArray = [car1, car2, car3, car4]

let prices = carsArray.map { $0.price! }
// prices = [35000, 25000, 47000, 27999]
let namesArray = carsArray.map { $0.name! }
var namesString = namesArray.joined(separator: ", ")
// Toyota, Nissan, Subaru, Honda

namesString = carsArray.map { $0.name! }.joined(separator: ", ")
// Toyota, Nissan, Subaru, Honda

Filter


Passes through the collection and returns a collection whose elements match the conditionю
// Example of using Filter function

let numbersArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
var filteredArray = [Int]()

// standard manner
for number in numbersArray {
    if number % 3 == 0 || number % 5 == 0 {
        filteredArray.append(number)
    }
}
// filteredArray = [3, 5, 6, 9, 10, 12, 15]

// using filter function
filteredArray = numbersArray.filter { $0 % 3 == 0 || $0 % 5 == 0 }
// filteredArray = [3, 5, 6, 9, 10, 12, 15]

// filter array of objects and then map this array to array of strings
// there is chaining of functions: filter > map
let lowPriceCars = carsArray.filter { $0.price! < 30000 }.map { $0.name! }
// lowPriceCars = ["Nissan", "Honda"]

Reduce


Combines the elements of a collection into a single value.
// Example of Reduce
let elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// standard manner
var sum = 0
for number in elements {
    sum += number
}
// sum = 55

// with using reduce
sum = elements.reduce(0, { $0 + $1} )
// sum = 55

sum = elements.reduce(0, +)
// sum = 55

let isAllCarsHasA = carsArray.reduce(true) { (hasA, car) in
    hasA && car.name.lowercased().contains("a")
}
//isAllCarsHasA = true


// using reduce to calculate average car price
// map array > reduce array values > divide
let averageCarPrice = carsArray.map { Float($0.price) }.reduce(0, +) / Float(carsArray.count)
// averageCarPrice = 33749.8

FlatMap

  1. When implemented on embedded collections flattens a result. If you have array of arrays then flatMap return array of elements of nested arrays.
  2. When used for a collection containing nils, it removes these nils.
// Example of Using FlatMap
var embeddedArray = [[1, 2, 3, 4], [5, 6, 7, 8]]
let flatArray = embeddedArray.flatMap { $0 }
// flatArray = [1, 2, 3, 4, 5, 6, 7, 8]

let carsAndNils = [car1, car2, nil, car4, nil, car3]
let validCars = carsAndNils.flatMap { $0?.name }
// validCars = ["Toyota", "Nissan", "Honda", "Subaru"]

Chaining functions


Also we can invoke next function on result of previous function.
// Chaining
let arrayOfArrays = [[1, 2, 3, 4], [55, 66, 77, 90], [15, 20, 30, 45]]
var resultOfChain = arrayOfArrays.flatMap { $0 }.filter { $0 % 2 == 0 }.reduce(0, +)
// resultOfChain = 212


5 comments:

  1. After a long time i found a unique and on purpose information about Custom Designed Websites. Can't wait to have more from you.

    ReplyDelete
  2. Thank you very much for drawing my notice to this. Your blog is jam-packed with helpful information. Unless I read it, I'd have no idea. I'll be back for more great content. Wishing you the best of luck and prosperity. Best Custom Websites

    ReplyDelete
  3. Thank you very much for sharing this informational blog.I could not find such kind of information in any other site.I'll come back for more fantastic material.
    Best wishes, and good luck.
    Custom Website

    ReplyDelete
  4. your article is unbelievable with accurate information. I see a lot of research after that and that is more than I expectedCustom Build Website

    ReplyDelete
  5. Great content. I was looking for this kind of content. It saved my time to search further.
    You must provide such type of content constantly. I appreciate your willingness to provide readers with a good article.
    Mobile Performance Meter HackYou made some good points there. I did a Google search about the topic and found most people will believe your blog

    ReplyDelete