简体   繁体   English

检查Array中的Int。 Swift 3,iOS

[英]Checking for Int in Array . Swift 3, iOS

I have the following code: 我有以下代码:

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
                }
            }

I am checking if sender.tag does equal to any of elements in array DictPl2. 我正在检查sender.tag是否等于数组DictPl2中的任何元素。 But if it does or doesn't equal, the code always goes the marked way. 但是,如果它相等或不相等,则代码总是按照标记的方式运行。 Anyone knows, what might be the mistake? 谁知道,这可能是什么错误? Thank you 谢谢

You can just use DictPl2.contains(sender.tag) instead of your for loop . 您可以只使用DictPl2.contains(sender.tag)而不是for loop Then your code would look like: 然后您的代码将如下所示:

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

In Swift 3.2 在Swift 3.2中

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

Please check Apple Guide . 请检查Apple Guide

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM