介紹高階功能

讓我們以一種場景來更好地理解推進功能,

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