繁体   English   中英

检查Array中的Int。 Swift 3,iOS

[英]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.

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