高阶函数:map、flatMap、compactMap
使用 Swift 的集合函数转换序列,而不进行变更。
高阶函数:map、flatMap、compactMap 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 4 节课。
欢迎
高阶函数接收或返回其他函数。Swift 的集合库建立在这些函数之上:`map`、`flatMap`、`compactMap`、`filter`、`reduce`。
map——转换每个元素
```swift
let nums = [1,2,3,4]
let squared = nums.map { $0 * $0 } // [1,4,9,16]
let strs = nums.map(String.init) // ["1","2","3","4"]
```
flatMap——转换并展平
```swift
let words = ["hello world","foo bar"]
let all = words.flatMap { $0.split(separator:" ").map(String.init) }
// ["hello","world","foo","bar"]
```
compactMap——转换并丢弃 nil
```swift
let mixed = ["1","two","3"]
let nums = mixed.compactMap { Int($0) } // [1,3]
```
传递函数引用
```swift
func double(_ n: Int) -> Int { n * 2 }
let result = [1,2,3].map(double) // [2,4,6]
```
函数引用可以替代闭包字面量。
链接高阶函数
```swift
let total = (1...100)
.filter { $0 % 2 == 0 }
.map { $0 * $0 }
.reduce(0, +)
// sum of squares of even numbers 1-100
```
对可选值使用 flatMap
```swift
let maybeStr: String? = "42"
let maybeInt = maybeStr.flatMap { Int($0) } // Optional(42)
let nil2: String? = nil
let also = nil2.flatMap { Int($0) } // nil
```
自定义高阶函数
```swift
func applyTwice(_ f: (T) -> T, _ value: T) -> T { f(f(value)) }
print(applyTwice({ $0 * 2 }, 3)) // 12
```
将 sorted(by:) 作为高阶函数
```swift
let words = ["banana","apple","cherry"]
let sorted = words.sorted { $0.count < $1.count }
// ["apple","banana","cherry"]
```
`sorted(by:)` 接受一个比较函数。
实践:处理用户数据
```swift
struct User { var name: String; var score: Int }
let users = [User(name:"A",score:80),User(name:"B",score:45),User(name:"C",score:92)]
let topNames = users.filter { $0.score >= 80 }.map { $0.name }.sorted()
// ["A","C"]
```
快速检查
`compactMap` 做了什么,而普通的 `map` 没有做?
回顾
要点:
• `map`——转换每个元素
• `flatMap`——转换并展平嵌套结果
• `compactMap`——转换并丢弃 nil
• 直接传递函数引用:`.map(String.init)`
• 链接这些函数,构建简洁的数据处理管道
下一步:函数组合与管道。
常见问题解答
「高阶函数:map、flatMap、compactMap」课时是免费的吗?
是的 — 「高阶函数:map、flatMap、compactMap」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 4 节课。
「高阶函数:map、flatMap、compactMap」这节课中我会学到什么?
使用 Swift 的集合函数转换序列,而不进行变更。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Swift Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「高阶函数:map、flatMap、compactMap」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Swift Academy 课中编写并运行代码吗?
能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 纯函数与无副作用设计
- 高阶函数:map、flatMap、compactMap
- 函数组合与数据管道
- 用于提升效率的惰性序列