在 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() 方法将结果转换为一个只包含值的数组。

相关推荐
_Voosk1 天前
macOS Xcode C++程序设置相对路径根目录
c语言·c++·xcode·swift
小锋学长生活大爆炸1 天前
【教程】MacOS绕过Apple Develop ID获取麦克风权限
macos·swift
JQShan2 天前
同步的 defer,异步的陷阱:Swift 并发中加载动画关不掉的调试实录
性能优化·swift
JQShan2 天前
Swift 多线程通关指南:从 GCD 回调地狱到 Task/Actor 躺赢
swift
Kyln.Wu2 天前
【python实用小脚本-292】[HR揭秘]手工党点名10分钟的终结者|Python版Zoom自动签到+名单导出加速器(建议收藏)
开发语言·python·swift
大熊猫侯佩2 天前
Swift 6.2 列传(第十四篇):岳灵珊的寻人启事与 Task Naming
swift·编程语言·apple
大熊猫侯佩2 天前
SwiftUI 涨知识:如何按条件动态切换 Toggle 视图的样式(.button 或 .switch)
swiftui·swift·apple
初级代码游戏5 天前
iOS开发 SwiftUI Text的基本用法
ios·swiftui·swift
Haha_bj6 天前
Swift——高阶函数(map、filter、reduce、forEach、sorted、contains……)
ios·app·swift