Swift_Array的几个高级函数map, filter, reduce

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jancywen/article/details/64461551


map映射一个新数组

在这个例子中,“map”将第一个数组中的 element 转换为小写的字符串,然后计算他们的characters

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.characters.count }
// 'letterCounts' == [6, 6, 3, 4]

API

	

    /// - Parameter transform: A mapping closure. `transform` accepts an

    ///   element of this sequence as its parameter and returns a transformed

    ///   value of the same or of a different type.

    /// - Returns: An array containing the transformed elements of this

    ///   sequence.

    public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]


filter 提取数组中满足条件的元素

在这个例子中,“filter”用于只包括短于5个字符的名称。

	let cast = ["Vivien", "Marlon", "Kim", "Karl"]
        let shortNames = cast.filter { $0.characters.count < 5 }
        print(shortNames)
        // Prints "["Kim", "Karl"]"

API

    /// - Parameter shouldInclude: A closure that takes an element of the
    ///   sequence as its argument and returns a Boolean value indicating
    ///   whether the element should be included in the returned array.
    /// - Returns: An array of the elements that `includeElement` allowed.
    public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]

reduce 将数组元素组合计算为一个值。这个例子展示了如何寻找一组数字的总和。

let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10
        
let sum =  numbers.reduce(0) { (sum, x) -> Int in
      sum + x
   }
// 'sum' == 10

//可以写成下面形式

sum = numbers.reduce(0,{$0 + $1})

sum = numbers.reduce(0,+)

API

    /// - Parameters:
    ///   - initialResult: the initial accumulating value.
    ///   - nextPartialResult: A closure that combines an accumulating
    ///     value and an element of the sequence into a new accumulating
    ///     value, to be used in the next call of the
    ///     `nextPartialResult` closure or returned to the caller.
    /// - Returns: The final accumulated value.
    public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result


猜你喜欢

转载自blog.csdn.net/jancywen/article/details/64461551
今日推荐