Higher-Order Functions in Swift

Save

As we have checked in our previous blog, we learned about some higher-order functions in swift.

In this blog, we are going to explore more Higher-Order functions in swift.

If you have not read our previous blog, please do check that blog as well from here.

Let’s start:

forEach-

forEach will iterate through all elements in an array. And unlike for in you can’t use a break and continue statement to exit from the closure for forEach.

Example:

Output: 1 3 8 5 6

Map-

As in our previos blog we have already learned about map, in this blog we will understand the types of map, i.e. compactMap and flatMap

compactMap-

The compactMap(_:) will iterate through all elements in an array and will remove nil values from the input array. It’s basically used when we are working with optionals.

Example:

Output: [1, 3, 5, 6]

flatMap-

flatMap converts 2D array to one-dimensional array.

Example:

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

sort(by:)-

sort(by:) will sort all elements according to the condition written inside the body of the closure in the same array.

Example:

Output: [8, 6, 5, 3 ,1]

sorted(by:)-

sorted(by:) will sort all elements according to the condition written inside the body of the closure and returns a new array.

Example:

Output:

numbers: [1, 3, 8, 5, 6]

sortedArray: [8, 6, 5, 3 ,1]

For more understanding of higher-order functions please check here.

For more interesting blogs check out here – https://mobikul.com/blog/.

Thanks for reading 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

Webkul is a truly trusted and supported IT Company to develop business ideas for e-commerce. They provide professional support after deploying the solution to production and be responsible to act for fixing the reported issues or system errors. We highly encourage to deal with Webkul for business development.

Hussein Zawia

Hussein Zawia

Co-founder, 24Dokan

Talk to Sales

Global

Live Chat
Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home