前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >swift Array map/flatMap/compactMap/filter/reduce/chaining用法小结

swift Array map/flatMap/compactMap/filter/reduce/chaining用法小结

作者头像
woopDast1
发布2021-04-12 11:12:37
3710
发布2021-04-12 11:12:37
举报
文章被收录于专栏:iOSer

之前特意了解过相关用法,但是时间久了容易忘记,故总结一下,方便回顾。

在playground中测试和注释如下:

代码语言:javascript
复制
import UIKit

let arr = [1,2,3]

//MARK:map(映射):returns an Array containing results of applying a transform to each item.
arr.map { (value) -> Int in
   return value * 2
}

arr.map { (value) -> Int in
    value * 2
}

//闭包写在一行时,执行4次,第一次是闭包赋值操作
arr.map { (value) in value * 2}

let arr1 = arr.map {
    $0 * 2
}

arr.map {$0 * 2}

let arr2 = arr.map {"\($0)"}
print(arr2)

let dic = ["point1" : 10, "point2" : 20, "point3" : 30]
dic.map { (name,distance) -> Int in//参数是元组
    distance * 2
}
dic.map {$0.1 * 2}

//MARK:filter:returns an Array containing only those items that match an include condition.
let arrF0 = arr.filter { (num) -> Bool in
    num % 2 == 0
}

let arrF1 = arr.filter { $0 % 2 == 0 }
print(arrF1)

//MARK:reduce(归纳):初始值+闭包("+"操作符本质也是闭包)。returns a single value calculated by calling a combine closure for each item with an initial value.
let sum = arr.reduce(10) {Result,num -> Int in
    Result + num
}
let sum1 = arr.reduce(10,+)

let dicR0 = dic.reduce("res:") { (Result, arg1) -> String in
    let (key, value) = arg1
    return Result + key + "\(value)" + ","
}

let dicR1 = dic.reduce("res:") { (Result, arg1) -> String in
    let (key, value) = arg1
    return key + "\(value)" + "!"
}

let arrStr = ["你", "好", "啊"]
let dicRStr0 = arrStr.reduce("归纳:"){res, str in res + str}
let dicRStr1 = arrStr.reduce("归纳:", +)

//MARK:flatMap(压平):二维数组降维成一维;可选值转换为可选值
let arrWithArr = [[1, 2], [3, 4, 5], [6, 7]]
let arrFm = arrWithArr.flatMap{$0}
print(arrFm)

let num: Int? = Int(8);
let numFM = num.flatMap{$0 < 5 ? $0 : nil}

//MARK:compactMap(紧凑):去 nil+变非可选
let arrWithNil: [String?] = ["1", nil, "2", nil]

//'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value
//arrWithNil.flatMap{$0}

let arrCm = arrWithNil.compactMap{$0}
print(arrCm)
 
//MARK:chaining(链式语法)
let resCh = arrWithArr.flatMap{$0}.filter{$0 > 5}.reduce(10, +)
print(resCh)

链接:swiftArrayMapAndso.playground

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-04-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档