2017-02-16 52 views
0

我有以下代碼:檢查數組中的Int。迅速3,iOS的

print (sender.tag) // prints 21 (example) 
print(DictPl2) // prints [0, 1, 20, 21, 84, 94, 26, 27, 37, 55, 56, 66, 52, 53, 54, 55, 72, 73, 74, 75] 
var DictPl2 = [Int]() 
if playeractive == 1 { 
for i in DictPl2 { 
       if i == sender.tag { 
        print("Well done") 
        sender.backgroundColor = UIColor.red 

       } 

       else { //always goes this 
        print("Bad") 
        sender.backgroundColor = UIColor.brown 
       } 
      } 

我檢查如果sender.tag確實等於任何在陣列DictPl2元件。但是如果它確實或不相等,代碼總是以標記的方式出現。任何人都知道,可能是什麼錯誤? 謝謝

+0

你還記錄我和日誌sender.tag嗎?可能是你沒有正確設置發件人的標籤? –

+3

請注意,您執行* all *數組元素的比較 - 最後一個元素獲勝! –

+0

我明白了,也謝謝! –

回答

5

您可以使用DictPl2.contains(sender.tag)而不是您的for loop。然後,你的代碼看起來像:

if DictPL2.contains(sender.tag) { 
    print("Well done") 
    sender.backgroundColor = UIColor.red 
} else { 
    print("Bad") 
    sender.backgroundColor = UIColor.brown 
} 
+0

好,作品,謝謝!但不知道爲什麼代碼不起作用。 –

+0

@TobyV。你能接受它作爲一個答案,因爲它的作品? :) –

+1

@StefanStefanov你可以使用三元運算符'sender.backgroundColor = DictPL2.contains(sender.tag)來簡化你的代碼? .red:.brown' –

0

在雨燕3.2

if DictPL2.contains(where: {$0 == sender.tag) { 
    print("Well done") 
} else { 
    print("Bad") 
} 

請檢查Apple Guide