检查数组是否包含Swift 4中的元素

Jum*_*dad 1 arrays swift

我正在尝试检查数组是否categories包含数字1 ,例如Int因为categories = [Int]()categories = {1, 2, 3, 4, 5}

我尝试了以下代码,这给了我错误 Binary operator '==' cannot be applied to operands of type 'Any' and 'Int'

if categories.contains (where: {$0 == 1}) {
    // 1 is found
}
Run Code Online (Sandbox Code Playgroud)

也尝试了没有下面的哪里和方括号的尝试,这给了我同样的错误

if categories.contains { $0 == 1 } {
    // 1 is found
}
Run Code Online (Sandbox Code Playgroud)

我尝试只使用以下元素,这给了我错误 Missing argument label 'where:' in call

if categories.contains(1) {
    // 1 is found
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Mal*_*lik 5

看来您的category数组是类型Any

修复方法


Jum*_*dad 0

感谢您的评论让我检查了数组的声明,问题是在[Any]我从UserDefaults. 我已经检查并找到了解决方案How do I save an Int array in Swift using NSUserDefaults?

// old declaration
let categories = userDefaults.array(forKey:"categories") ?? [Int]()

// new correct declaration
var categories = [Int]()
if let temp = userDefaults.array(forKey:"categories") as? [Int] {
    categories = temp
}
Run Code Online (Sandbox Code Playgroud)