在 Swift 中, enumerated() 有哪些常用的使用方式 ?

enumerated() 是什么 ?

  1. enumerate, 词性为 VERB, 中文译为"列举;枚举", When you enumerate a list of things, you name each one in turn.

  2. enumerated, 是 enumerate 的过去式和过去分词

  3. 对于 enumerated() 方法, 苹果官方的描述是: Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

swift 复制代码
// enumerated()接口声明
func enumerated() -> EnumeratedSequence<Self>
// EnumeratedSequence接口声明
public struct EnumeratedSequence<Base> where Base : Sequence

在 Swift 中,enumerated() 是一个用于遍历集合类型的方法,它返回一个由每个元素的索引和值组成的元组。

常用的使用方式 (或使用场景)

  1. 遍历数组并获取元素的索引和值:
swift 复制代码
let array = ["apple", "banana", "orange"]
for (index, value) in array.enumerated() {
    print("Index: \(index), Value: \(value)")
}

输出:

复制代码
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
  1. 使用 map() 方法将数组中的元素转换为元组:
swift 复制代码
let array = ["apple", "banana", "orange"]
let enumeratedArray = array.enumerated().map { (index, value) in
    return (index: index, fruit: value)
}
print(enumeratedArray)

输出:

复制代码
[(index: 0, fruit: "apple"), (index: 1, fruit: "banana"), (index: 2, fruit: "orange")]
  1. 使用 filter() 方法过滤数组中的元素:
swift 复制代码
let array = ["apple", "banana", "orange"]
let filteredArray = array.enumerated().filter { (index, value) in
    return index % 2 == 0
}.map { (index, value) in
    return value
}
print(filteredArray)

输出:

复制代码
["apple", "orange"]

在这个例子中,我们使用 filter() 方法过滤了索引为偶数的元素,并使用 map() 方法将结果转换为一个只包含值的数组。

相关推荐
2501_9159090620 小时前
原生 iOS 开发全流程实战,Swift 技术栈、工程结构、自动化上传与上架发布指南
android·ios·小程序·uni-app·自动化·iphone·swift
大熊猫侯佩1 天前
月球矩阵日志:Swift 6.2 主线程隔离抉择(下)
swift·编程语言·apple
大熊猫侯佩1 天前
月球矩阵日志:Swift 6.2 主线程隔离抉择(上)
swift·编程语言·apple
HarderCoder1 天前
Swift 并发深度指南:非结构化任务与分离任务全解析
swift
HarderCoder1 天前
Swift 6 新关键字 `sending` 深度指南——从 `@Sendable` 到 `sending` 的进化之路
swift
Mr_zheng1 天前
iOS 26 UIKit和Swift上的更新
ios·swift
YungFan1 天前
iOS26适配指南之UISearchController
ios·swift
东坡肘子2 天前
高通收购 Arduino:历史的轮回 | 肘子的 Swift 周报 #0106
swiftui·arduino·swift
HarderCoder2 天前
Swift 基础语法全景(二):可选型、解包与内存安全
swift
HarderCoder2 天前
Swift 基础语法全景(三):元组、错误处理与断言
swift