[英]Checking for Int in Array . Swift 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中的任何元素。 但是,如果它相等或不相等,則代碼總是按照標記的方式運行。 誰知道,這可能是什么錯誤? 謝謝
您可以只使用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
}
在Swift 3.2中
if DictPL2.contains(where: {$0 == sender.tag) {
print("Well done")
} else {
print("Bad")
}
請檢查Apple Guide 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.