2016-10-11 75 views
0

,如果我有兩個數組&我想比較它們的索引,例如:斯威夫特3個比較數組索引

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

,我想打印的東西說哪個指數不一樣的,如:

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

將我不得不寫7個那些語句,以顯示正確的/都錯了/指數1點& 1錯了,等所有8種可能性?

謝謝!如果你發現自己重複同樣的代碼,但是有不同的號碼,你可以用一個for循環替換它

for i in 0..<a1.length { 
    if a1[i] != a2[i] { 
     print("Index \(i) is not the same") 
    } 
} 

一般:

回答

8

你可以得到所有的指標是這樣的:

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

說明:

  • zip產生對
  • enumerated()的序列添加一個索引序列
  • filter只保留對具有不同的值
  • map收穫指數,並建立結果序列。

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

這將產生一個序列運行此[0, 3]

0

使用for循環。

+0

謝謝!如果值是字符串而不是整數,那麼對於循環是否會起作用? – 3Beard

+1

@ 3Beard只要可以應用'!='運算符,此循環不會對「a1」和「a2」元素的類型作出任何假設。 – dasblinkenlight

0

試試這個

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

let result = zip(a1, a2).map({ $0 == $1 }).reduce(true, {$0 && $1}) 
0

當然,你可以做這樣的事情:

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

var compareResult : [String] = [String]() 

if a1.count == a2.count { // Need to check they have same length 

    for count in 0..<a1.count { 
     let result : String = a1[count] == a2[count] ? "MATCH" : "MISMATCH" 
     compareResult.append(result) 
    } 

    print(compareResult) 
    // Do something more interesting with compare result... 
}