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

相关推荐
一丝晨光2 天前
继承、Lambda、Objective-C和Swift
开发语言·macos·ios·objective-c·swift·继承·lambda
KWMax2 天前
RxSwift系列(二)操作符
ios·swift·rxswift
Mamong2 天前
Swift并发笔记
开发语言·ios·swift
小溪彼岸3 天前
【iOS小组件】小组件尺寸及类型适配
swiftui·swift
Adam.com3 天前
#Swift :回调地狱 的解决 —— 通过 task/await 来替代 nested mutiple trailing closure 来进行 回调的解耦
开发语言·swift
Anakki3 天前
【Swift官方文档】7.Swift集合类型
运维·服务器·swift
KeithTsui4 天前
集合论(ZFC)之 联合公理(Axiom of Union)注解
开发语言·其他·算法·binder·swift
東三城4 天前
【ios】---swift开发从入门到放弃
ios·swift
文件夹__iOS7 天前
[SwiftUI 开发] @dynamicCallable 与 callAsFunction:将类型实例作为函数调用
ios·swiftui·swift