swift使用小技巧(4.0)

2017-12-27  本文已影响0人  yuandiLiao
1.查找元素查找在数组中的下标

例如在 数组a = [1,2,3,4,5] 查找元素3的下标

        //使用数组array遍历一遍,如果遍历到的值等于元素,那么闭包中返回true,index找到下标,不然就接着遍历
        if let index = a.index(where: {
            $0 == 3
        }) {
            print(index)
        }
        //item 是遍历a的元素,和需要找下标的元素判断。上面$0的写法是用闭包的特有写法,用来代替item,即代理闭包的参数
        if let index = a.index(where: { (item) -> Bool in
            item == 3
        }){
            print(index)
        }
2.从指定下标遍历数组
  //遍历除了最后n个元素外的数组
     for item in a.dropLast(n) {
            print(item)
        }
//遍历除了前面n个元素外的数组
     for item in a.dropFirst(n) {
           print(item)
       }
3.遍历数组中的元素和对应的下标
for (index,value) in a.enumerated() {
        
   }
3.使用filter条件过滤,得到新的数组
 let nums = [1,2,3,4,5,6,7,8,9,10]
 let arr = nums.filter { (num) -> Bool in
            num % 2 == 0
        }
//nums = [1,2,3,4,5,6,7,8,9,10]
//arr = [2, 4, 6, 8, 10]
3.使用map遍历数组元素,对元素进行操作,得到新数组
let a = [1,2,3]
 let squares = a.map{b -> Int in
            return b * b 
        }
// a = [1,2,3]
//squares = [1,4,9]
上一篇下一篇

猜你喜欢

热点阅读