Swift's detailed five-----------Map,filter,reduce

Source: Internet
Author: User

Map,filter,reduce

注:本文为作者自己总结,过于基础的就不再赘述 ,都是亲自测试的结果。如有错误或者遗漏的地方,欢迎指正,一起学习。

关于Swift 中String 、数组 、字典的基本用法这里就不再赘述了,这些都很简单 不会的 在用得时候baidu下就行了。这里主要看下这几个高阶函数
Map
map方法,其获取一个闭包表达式作为其唯一参数。 数组中的每一个元素调用一次该闭包函数,并返回该元素所映射的值(也可以是不同类型的值)。 具体的映射方式和返回值类型由闭包来指定。当提供给数组闭包函数后,map方法将返回一个新的数组,数组中包含了与原数组一一对应的映射后的值。来看看map的定义 `func map(transform: (T) -> U) -> U[]`  ,这里 `T`    和 `U` 都是泛型 ,指一种类型 , `T`    和 `U` 只两个不同的类型 ,也可以相同 。来看个例子 :我们用一个Int类型数组存储商品金额,想把每个金额前面添加一个字符“¥”
let prices = [10,20,30]let"¥\($0)" }  
这个语法大家应该不陌生吧 ,陌生的去把上节闭包重新看一遍因为map只有一个参数,后面直接用了闭包的尾随 ,不会加括号了得到的结果 :`print(strPrices)  //[¥10, ¥20, ¥30]` 这只是一个简单的实例 ,其实你可以对每个元素进行很复杂的运算,这里不再赘述 ,用法如此,点到为止 、哈哈
Filter
let p = [10,20,33,44,87,15]let$0>20 }
得到结果 :print(res) //[33, 44, 87]是不是用起来很方便呀!!
Reduce
reduce方法把数组元素组合计算为一个值,并且会接受一个初始值,这个初始值得类型可能和数组元素类型不同。来看定义 。reduce(initial: U, combine: (U, T) -> U) -> U不同的大写字母当成不同的类型看待。来看实例
let p1 = [20,20,10]let sum = p1.reduce(0$0+$1 }print(sum) //50
这个实例给了个初始为Int类型的 0 ,用这个  
let sum2 = p1.reduce(4$0+$1 }print//54
初始值换成4 就会得到这样的结果 ,是不是也不是那么难理解呀!
let sum1 = p1.reduce("2"" \($0) , \($1)" }print(sum1) //  2202010
如果初始值是一个字串就不能用加法了。不过可以拼接得到上面的结果 。map和filter都很好理解 ,reduce稍微难理解一点 需要说明的是数据比较大的时候,高阶函数会比传统实现更快,因为它可以并行执行(如运行在多核上),除非真的需要更高定制版本的map,reduce和filter,否则可以一直使用它们以获得更快的执行速度希望以上的实例可以帮助大家更好的理解这几个函数!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Swift's detailed five-----------Map,filter,reduce

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.