在Swift中使用索引映射或减少

前端之家收集整理的这篇文章主要介绍了在Swift中使用索引映射或减少前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有一种方法获取数组的索引在map或reduce在Swift?我在Ruby中寻找类似each_with_index的东西。
  1. func lunhCheck(number : String) -> Bool
  2. {
  3. var odd = true;
  4. return reverse(number).map { String($0).toInt()! }.reduce(0) {
  5. odd = !odd
  6. return $0 + (odd ? ($1 == 9 ? 9 : ($1 * 2) % 9) : $1)
  7. } % 10 == 0
  8. }
  9.  
  10. lunhCheck("49927398716")
  11. lunhCheck("49927398717")

我想摆脱奇变量above

您可以使用枚举将序列(Array,String等)转换为具有整数计数器和元素配对在一起的元组序列。那是:
  1. let numbers = [7,8,9,10]
  2. let indexAndNum: [String] = numbers.enumerate().map { (index,element) in
  3. return "\(index): \(element)"
  4. }
  5. print(indexAndNum)
  6. // ["0: 7","1: 8","2: 9","3: 10"]

Link to enumerate definition

注意,这不同于获取集合枚举的索引返回一个整数计数器。这与数组的索引相同,但是对字符串或字典将不是非常有用。要获取实际的索引以及每个元素,您可以使用zip:

  1. let actualIndexAndNum: [String] = zip(numbers.indices,numbers).map { "\($0): \($1)" }
  2. print(actualIndexAndNum)
  3. // ["0: 7","3: 10"]

当使用带有reduce的枚举序列时,您将无法分离元组中的索引和元素,因为您在方法签名中已经有accumulating / current元组。相反,你需要在你的reduce闭包的第二个参数上使用.0和.1:

  1. let summedProducts = numbers.enumerate().reduce(0) { (accumulate,current) in
  2. return accumulate + current.0 * current.1
  3. // ^ ^
  4. // index element
  5. }
  6. print(summedProducts) // 56

猜你在找的Swift相关文章