您可以使用enumerate
将序列(Array
、String
等)转换为元组序列,其中整数计数器和元素配对在一起.也就是说:
let numbers = [7, 8, 9, 10]
let indexAndNum: [String] = numbers.enumerate().map { (index, element) in
return "\(index): \(element)"
}
print(indexAndNum)
// ["0: 7", "1: 8", "2: 9", "3: 10"]
Link to enumerate
definition
请注意,这与获取集合的index不同——enumerate
返回一个整数计数器.这与数组的索引相同,但在字符串或字典上不会很有用.要获得每个元素的实际索引,可以使用zip
:
let actualIndexAndNum: [String] = zip(numbers.indices, numbers).map { "\($0): \($1)" }
print(actualIndexAndNum)
// ["0: 7", "1: 8", "2: 9", "3: 10"]
当使用带有reduce
的枚举序列时,您将无法在元组中分离索引和元素,因为在方法签名中已经有了累积/当前元组.相反,您需要在reduce
闭包的第二个参数上使用.0
和.1
:
let summedProducts = numbers.enumerate().reduce(0) { (accumulate, current) in
return accumulate + current.0 * current.1
// ^ ^
// index element
}
print(summedProducts) // 56
Swift 3.0 and above
因为Swift 3.0的语法非常不同
let numbers = [7, 8, 9, 10]
let array: [(Int, Int)] = numbers.enumerated().map { ($0, $1) }
// ^ ^
// index element
这就产生了:
[(0, 7), (1, 8), (2, 9), (3, 10)]