Swift 函数Count,Filter,Map,Reduce

原创Blog,转载请注明出处
blog.csdn.net/hello_hwc

前言:和OC不同,Swift有很多全局的函数,这些全局函数对简化代码来说很有用,目前Swift出到了2.0,不过我这篇文章还是用Swift1.2写的示例代码

Count-统计数量

文档

func count<T : _CollectionType>(x: T) -> T.Index.distance

Description 
Return the number of elements in x.
O(1) if T.Index is RandomAccessIndexType; O(N) otherwise.

示例

let arr = [1,2,3,4]
 let dic = [1:2,"a":"b"]
 let str = "Wenchenhuang"
 println(count(arr))//4
 println(count(dic))//2
 println(count(str))//12

Filter-条件过滤

文档

func filter<S : SequenceType>(source: S,includeElement: (S.Generator.Element) -> Bool) -> [S.Generator.Element]

Description 
Return an Array containing the elements of source,in order,that satisfy the predicate includeElement.

示例-过滤长度大于4的字符串

let array = ["Wen","Chen","Huang"]
 let filteredArray =  filter(array,{ (element:String) -> Bool in return count(element)>4; }) println(filteredArray)

也可以简化

let filteredArray =  filter(array) {count($0)>4}

Map - 映射集合类型,返回数组

文档

func map<C : CollectionType,T>(source: C,transform: (C.Generator.Element) -> T) -> [T]
Description 

Return an Array containing the results of mapping transform over source.

示例

let array = ["Wen","Huang"]
let mapedaray = map(array,{ (element:String) -> Int in return count(element) }) println(mapedaray) //[3,4,5]

同样可以简化

let mapedaray = map(array){count($0)}

Reduce - 把数组结合到一起

文档

func reduce<S : SequenceType,U>(sequence: S,initial: U,combine: @noescape (U,S.Generator.Element) -> U) -U

Description 
Return the result of repeatedly calling combine with an accumulated value initialized to initial and each element of `sequence`,in turn.

示例

let array = ["Wen","Huang"]
 let reduceResult = reduce(array,"Hello ") { (originValue:String,element:String) -> String in
    return originValue + element;
 }
 println(reduceResult) //Hello WenChenHuang

可以简化

let reduceResult = reduce(array,"Hello ") { $0 + $1}

进一步简化

let reduceResult = reduce(array,"Hello ",+)

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...