加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 函数Count,Filter,Map,Reduce

发布时间:2020-12-14 02:01:36 所属栏目:百科 来源:网络整理
导读:原创Blog,转载请注明出处 blog.csdn.net/hello_hwc 前言:和OC不同,Swift有很多全局的函数,这些全局函数对简化代码来说很有用,目前Swift出到了2.0,不过我这篇文章还是用Swift1.2写的示例代码。 Count-统计数量 文档 func countT : _CollectionType (x:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读