Swift 3比较数组索引 [英] Swift 3 comparing array indexes

查看:65
本文介绍了Swift 3比较数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个数组&我想比较一下它们的索引,例如:

If i have two arrays & i want to compare their indexes, for ex:

let var a1 = ["1", "2", "3"]
let var a2 = ["3", "2", "3"]

我想打印出一些内容来说明哪个索引不相同,例如:

And i wanted to print something to say which index wasn't the same, such as:

if a1[0] != a2[0] && a1[1] == a2[1] && a1[2] == a2[2]{
print("Index 0 is not the same.")

我是否还要再编写7条语句以显示所有8种可能性,即所有正确/全部错误/索引1& 1错误,等等?

Would i have to write 7 more of those statements to show all 8 possibilities of all correct/all wrong/index 1&1 wrong, etc?

谢谢!

推荐答案

您可以获得所有这样的索引:

You can get all indexes like this:

let diffIndex = zip(a1, a2).enumerated().filter {$1.0 != $1.1}.map {$0.offset}

说明:


  • zip 产生一对序列

  • enumerated()向该序列添加索引

  • 过滤器仅保留具有不同值的对

  • map

  • zip produces a sequence of pairs
  • enumerated() adds an index to the sequence
  • filter keeps only pairs with different values
  • map harvests the index, and builds the sequence of results.

在其上运行

let a1 = ["1", "2", "3", "4"]
let a2 = ["3", "2", "3", "5"]

这将产生一个序列 [0,3]

这篇关于Swift 3比较数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆