Introduction with advance functions

suggest change

Let’s take an scenario to understand advance function in better way,

struct User {
    var name: String
    var age: Int
    var country: String?
}

//User's information 
let user1 = User(name: "John", age: 24, country: "USA")
let user2 = User(name: "Chan", age: 20, country: nil)
let user3 = User(name: "Morgan", age: 30, country: nil)
let user4 = User(name: "Rachel", age: 20, country: "UK")
let user5 = User(name: "Katie", age: 23, country: "USA")
let user6 = User(name: "David", age: 35, country: "USA")
let user7 = User(name: "Bob",age: 22, country: nil)

//User's array list
let arrUser = [user1, user2, user3, user4, user5, user6, user7]

Map Function:

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.

//Fetch all the user's name from array 
let arrUserName = arrUser.map({ $0.name }) // ["John", "Chan", "Morgan", "Rachel", "Katie", "David", "Bob"]

Flat-Map Function:

The simplest use is as the name suggests to flatten a collection of collections.

// Fetch all user country name & ignore nil value.
let arrCountry = arrUser.flatMap({ $0.country }) // ["USA", "UK", "USA", "USA"]

Filter Function:

Use filter to loop over a collection and return an Array containing only those elements that match an include condition.

// Filtering USA user from the array user list.
let arrUSAUsers = arrUser.filter({ $0.country == "USA" }) // [user1, user5, user6]

// User chaining methods to fetch user's name who live in USA 
let arrUserList = arrUser.filter({ $0.country == "USA" }).map({ $0.name }) // ["John", "Katie", "David"]

Reduce:

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

Swift 2.3:-

//Fetch user's total age.
let arrUserAge = arrUser.map({ $0.age }).reduce(0, combine: { $0 + $1 }) //174

//Prepare all user name string with seperated by comma 
let strUserName = arrUserName.reduce("", combine: { $0 == "" ? $1 : $0 + ", " + $1 }) // John, Chan, Morgan, Rachel, Katie, David, Bob

Swift 3:-

//Fetch user's total age.
let arrUserAge = arrUser.map({ $0.age }).reduce(0, { $0 + $1 }) //174

//Prepare all user name string with seperated by comma 
let strUserName = arrUserName.reduce("", { $0 == "" ? $1 : $0 + ", " + $1 }) // John, Chan, Morgan, Rachel, Katie, David, Bob

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents