介绍高级功能

让我们以一种场景来更好地理解推进功能,

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 循环遍历集合,并将相同的操作应用于集合中的每个元素。map 函数返回一个数组,其中包含将映射或转换函数应用于每个项目的结果。

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

平面地图功能:

最简单的用途是顾名思义压缩集合的集合。

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

过滤功能:

使用 filter 循环遍历集合并返回仅包含与 include 条件匹配的元素的 Array。

// 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 组合集合中的所有项目以创建单个新值。

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