微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 ",+)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐