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

来源:互联网 发布:激战2诺恩男捏脸数据 编辑:程序博客网 时间:2024/06/06 01:52


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

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo; color: #008f00}p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo; color: #000000}span.s1 {font-variant-ligatures: no-common-ligatures; color: #000000}span.s2 {font-variant-ligatures: no-common-ligatures}span.s3 {font-variant-ligatures: no-common-ligatures; color: #0433ff}span.s4 {font-variant-ligatures: no-common-ligatures; color: #3495af}

    /// - 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
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo; color: #000000}p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Menlo; color: #000000; min-height: 14.0px}span.s1 {font-variant-ligatures: no-common-ligatures}

//可以写成下面形式

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


0 0
原创粉丝点击