Swift 函数Count,Filter,Map,Reduce

前端之家收集整理的这篇文章主要介绍了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 ",+)

猜你在找的Swift相关文章