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

  • 相关阅读:
    iOS7,iOS8和iOS9的区别
    NSUrl
    什么是 MIME TYPE?
    TCP协议与UDP协议的区别
    KVC、KVO、NSNotification、delegate 总结及区别
    cocoapods 安装过程及常见问题
    素材丶资料
    方法 笔记(二)
    UIWebView UITextView
    在oj中Python的循环输入问题解决
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7160505.html
Copyright © 2020-2023  润新知