实例方法
enumerated()
返回一个对序列(
n
、x
),其中 n
表示从零开始的连续整数,而 x
表示序列的一个元素。声明
func enumerated() -> EnumeratedSequence<Self>
返回值
枚举序列的对序列。
详述
此示例枚举字符串 “Swift” 的字符并打印每个字符及其在字符串中的位置。
for (n, c) in "Swift".enumerated() {
print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"
枚举集合时,每对的整数部分是枚举的计数器,但不一定是配对值的索引。这些计数器只能在从零开始的 integer-indexed 集合的实例中用作索引,例如 Array
和 ContiguousArray
。对于其他集合,计数器可能超出范围或用作索引的类型错误。要使用其索引迭代集合的元素,请使用 zip(_:_:)
函数。
此示例遍历集合的索引和元素,构建一个列表,该列表由具有五个或更少字母的名称索引组成。
let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
var shorterIndices: [Set<String>.Index] = []
for (i, name) in zip(names.indices, names) {
if name.count <= 5 {
shorterIndices.append(i)
}
}
现在 shorterIndices
数组保存了 names
集合中较短名称的索引,您可以使用这些索引来访问集合中的元素。
for i in shorterIndices {
print(names[i])
}
// Prints "Sofia"
// Prints "Mateo"
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相关用法
- Swift AnyBidirectionalCollection elementsEqual(_:)用法及代码示例
- Swift AnyBidirectionalCollection lexicographicallyPrecedes(_:)用法及代码示例
- Swift AnyBidirectionalCollection split(separator:maxSplits:omittingEmptySubsequences:)用法及代码示例
- Swift AnyBidirectionalCollection sorted()用法及代码示例
- Swift AnyBidirectionalCollection shuffled(using:)用法及代码示例
- Swift AnyBidirectionalCollection starts(with:)用法及代码示例
- Swift AnyBidirectionalCollection contains(where:)用法及代码示例
- Swift AnyBidirectionalCollection suffix(from:)用法及代码示例
- Swift AnyBidirectionalCollection first用法及代码示例
- Swift AnyBidirectionalCollection prefix(through:)用法及代码示例
- Swift AnyBidirectionalCollection min()用法及代码示例
- Swift AnyBidirectionalCollection compactMap(_:)用法及代码示例
- Swift AnyBidirectionalCollection joined()用法及代码示例
- Swift AnyBidirectionalCollection indices用法及代码示例
- Swift AnyBidirectionalCollection subscript(_:)用法及代码示例
- Swift AnyBidirectionalCollection sorted(by:)用法及代码示例
- Swift AnyBidirectionalCollection split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代码示例
- Swift AnyBidirectionalCollection lastIndex(of:)用法及代码示例
- Swift AnyBidirectionalCollection firstIndex(of:)用法及代码示例
- Swift AnyBidirectionalCollection last(where:)用法及代码示例
- Swift AnyBidirectionalCollection randomElement(using:)用法及代码示例
- Swift AnyBidirectionalCollection max(by:)用法及代码示例
- Swift AnyBidirectionalCollection isEmpty用法及代码示例
- Swift AnyBidirectionalCollection last用法及代码示例
- Swift AnyBidirectionalCollection flatMap(_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 AnyBidirectionalCollection enumerated()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。