简体   繁体   中英

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

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

Please check Apple Guide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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