1. filter (过滤器):返回符合条件的一个数组
                let arr = [1,5,6,7,10,0]
               //写法1
                let arr1 = arr.filter { (item) -> Bool in
                    return item % 2 == 0
                }
               
                 //写法2
                let resultArray = arr.filter { return $0%2 == 0 }
    
                 //写法3
                let arr2 = arr.filter({return $0%2 == 0})

  

2.index(符合条件的索引):返回int值
                let arr = [1,5,6,7,10,0]
                //写法1:swift 4.0
                let index = arr.index(where: {$0 == 1})
                
                //swift4.2  firstIndex:从前往后遍历,
                let index2 = arr.firstIndex(where:{$0 == 1})
                let index3 = arr.firstIndex { (item) -> Bool in
                    return item == 1
                }
                
                //lastIndex:c从后往前遍历
                let index4 = arr.lastIndex(where:{$0 == 1})
                
                let index5 = arr.lastIndex(of: 5)
                if index5 != nil{
                    print("打印一下")
                }

  

3. contains(包含):返回bool值
                let arr = [1,5,6,7,10,0]
                //写法1
                let isContains = arr.contains(where: {$0 == 3})
                //写法2
                let isContains1 = arr.contains { (item) -> Bool in
                    return item == 100
                }
                //写法3 直接调用函数
                 arr.contains(10)
                print(arr.contains(3))

  

4. foreach: 和for in快速遍历 类似, 但是return 条件时,返回不一样

        if self.view.subviews.count > 0{
            self.view.subviews.forEach({$0.removeFromSuperview()})
        }

注意点:
在使用return关键字的时候,很明显,for in中是当符合当前执行语句时,程序直接终止到此并返回, 比如上面的元素 "4"、"5"、"Hello World" 没有被执行;而forEach中是当符合当前执行语句时,程序跳过本次判断继续执行, 比如上面的元素"4"、"5"、"Hello World"被执行。
foreach: 和for in 具体区别:https://www.jianshu.com/p/0f75c23773b5

  

 

 

数组的  compactMap 添加每个元素

 let numberArr :[Substring]= “123,5215614,”.split(separator: ",")
 
 let arrayStrings: [String] = numberArr.compactMap { "\($0)" }

 

posted on 2018-10-23 11:50  懂事长qingzZ  阅读(312)  评论(0编辑  收藏  举报