Introduction to advanced functions
suggest changeTake this scenario as a way to see how these functions work:
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 every user's name from the array
let arrUserName = arrUser.map({ $0.name }) // ["John", "Chan", "Morgan", "Rachel", "Katie", "David", "Bob"]
Flat-Map Function:
On a sequence of optionals, flatMap drops nil and unwraps the rest. Swift 4.1 and later name that operation compactMap. A different flatMap overload flattens a collection of collections.
// Country names, with nil values left out.
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]
// Chain the methods to fetch the names of users who live in the 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
// Join the user names with a 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
// Join the user names with a comma
let strUserName = arrUserName.reduce("", { $0 == "" ? $1 : $0 + ", " + $1 }) // John, Chan, Morgan, Rachel, Katie, David, Bob
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents