在 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.

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

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

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

  1. 遍历数组并获取元素的索引和值:
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() 方法将数组中的元素转换为元组:
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() 方法过滤数组中的元素:
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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

依旧风轻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值