Skip to main content

Swift Higher Order Functions Filter, Map, Reduce, Flatmap and CompactMap

Map, filter, reduce, Flatmap and  CompactMap drop in Swift. Simple Higher Order Function

Higher order functions are simply functions that operate on other functions by either taking a function or closures as an argument, or returning a function. That can be used on collection types such as Array or Dictionary

Higher Order Functions

Map : - "Use map to loop over a collection and apply the same operation to each element in the collection. The map function returns an array containing the results of applying a mapping or transform function to each item:"

That used for-loop- 

let arrays = [2.0,4.0,5.0,7.0]
var arraySquar: [Double] = []
for value in arrays {
  arraySquar.append(value*value)
}
// [4.0, 16.0, 25.0, 49.0]

Now With map
let arrays = [2.0,4.0,5.0,7.0]

let arraySquar= arrays .map {$0 * $0}

// [4.0, 16.0, 25.0, 49.0]

let scores = [0,28,124]
let words = scores.map { NumberFormatter.localizedString(from: $0 as NSNumber, number: .spellOut) }
print(words)

// ["zero", "twenty-eight", "one hundred twenty-four"]

Filter :- Use filter to loop over a collection and return an Array containing only those elements that match an include condition and must return a Bool indicating if the item should be included in the result.
x = 3, 4, 10, 17
if x % 2 == 0
then match = 4, 10
Example - 
let values= [3,4,10,21, 22]
let even = digits.filter { $0 % 2 == 0 }
// [4, 10, 22]

Reduce : -  Use reduce to combine all items in a collection to create a single new value.

let items = [2.0,4.0,5.0,7.0]
let total = items.reduce(10.0, +)
// 28.0

This will also work with strings using the + operator to concatenate:

let codes = ["abc","def","ghi"]
let text = codes.reduce("", +)
// "abcdefghi"

The combine argument is a closure so you can also write reduce using the trailing closure syntax:

let names = ["alan","brian","charlie"]
let csv = names.reduce("===") {text, name in "\(text),\(name)"}
// "===,alan,brian,charlie"

FlatMap and CompactMap

Flatmap
Flatmap is used to flatten a collection of collections . But before flattening the collection, we can apply map to each elements.

"Using FlatMap on a sequence with a closure that returns a sequence"
let results = [[5,2,7], [4,8], [9,1,3]]
let allResults = results.flatMap { $0 }
// [5, 2, 7, 4, 8, 9, 1, 3]

let passMarks = results.flatMap { $0.filter { $0 > 5} }
// [7, 8, 9]

let codes = [["abc", "def", "ghi"], ["abc", "def", "ghi"]]
let newCodes = codes.flatMap{ $0.map { $0.uppercased90}}
print(newCodes)

// ["ABC", "DEF", "GHI", "ABC", "DEF", "GHI"]

if newCodes  = codes.flatMap{ $0.uppercased()}
print(newCodes)

// ["A", "B", "C", "D", "E", "F", "G", "H", "I"]

Using FlatMap on an optional:
let input: Int? = Int("8")
let passMark: Int? = input.flatMap { $0 > 5 ? $0 : nil }
// 8
Using CompactMap on a sequence with a closure that returns an optional.

Note that this use of flatMap was renamed to compactMap in Swift 4.1 (Xcode 9.3). It provides a convenient way to strip nil values from an array:
let keys: [String?] = ["Tom", nil, "Peter", nil, "Harry"]
let validNames = keys.compactMap { $0 }
validNames

// ["Tom", "Peter", "Harry"]

let counts = keys.compactMap { $0?.count }
counts
// [3, 5, 5]






Comments

  1. I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.
    Mobile App Development Company In Chennai
    Android App Development Company In Chennai
    Android Application Development Company In Chennai
    Mobile App Development Company In India

    ReplyDelete

Post a Comment

Popular posts from this blog

Add a Scene Delegate to your existing project with Storyboard in Swift

To add a scene delegate, first, create a new Swift file that you’ll call "SceneDelegate" containing a subclass of UIResponder, just like the AppDelegate, and that conforms to UIWindowSceneDelegate.  As your app might supports other versions than iOS 13, make this class only available for iOS 13. This is what you should have : If you are working a project that is storyboard based, please set storyboard  initial view controller SceneDelegate.swift import UIKit @available ( iOS 13.0 , *) class SceneDelegate : UIResponder , UIWindowSceneDelegate {     var window : UIWindow ?     func scene ( _ scene: UIScene , willConnectTo session: UISceneSession , options connectionOptions: UIScene . ConnectionOptions ) {                  let storyboard = UIStoryboard (name: "Main" , bundle: nil )         let initialViewController = storyboard. instantiateViewController (withIdentifier: "ViewController" )         let mainNavigationController = UINavigationControlle

How Create Animated Circle Progress Bar iOS 11 Swift 4

  Animated Circle Progress Bar iOS 11 Swift 4 With MBCircularProgressBa r - https://github.com/MatiBot/MBCircularProgressBar A circular, animatable & highly customizable progress bar from the Interface Builder Swift, Using pod fite MBCircularProgressBar Installation Cocoapods terminal. pod "MBCircularProgressBar" That - A Simple Steps to installed pod file -        Open terminal        Command on terminal go to project folder Cd path        set your project path on terminal.        command : pod init        open pod file - open -e podfile        added in pod file with in : pod "MBCircularProgressBar"        Command : Pod install        Close project of Xcode        open your Project from terminals        Command : open PodDemos.xcworkspace After opern StoryBoard and Now drag a UIView over the viewController in storyboard Or set UIView Constraint width, height or verticle or horzentail space and set a class MBCircul

How to Use Multiple Sections in UITableView iOS Swift !

Multiple sections in UITableView iOS Swift. UITableView is very important part of iOS ecosystem. So we split tableviews in sections. Then its easier to find right information.  1. First let’s create a project as usual. Create a new single view application X code project. Set project name to UIViewController.  2. Go to main storyboard & select view controller & use UITableView 3. Select tableview & make it initial view controller  4 Create a custom Sections Class like Name => TableSections, create register cell static return “ getCellNibs ” method. Then create  4 section enum “TableItems” then after append all sections to an array model. import UIKit struct CellNib {      static func getCellNibs () -> [ String ] {          return [ "Cell1" , "Cell2" , "Cell3" , "Cell4" ]     } } enum TableItems : Int {      case TableSections1      case TableSections2      case TableSections3      case TableSections4 } class TableSec