我正在尝试检查数组是否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)
我怎样才能做到这一点?
看来您的category数组是类型Any
修复方法
您可以将数组声明为Int数组
var categories: [Int]
Run Code Online (Sandbox Code Playgroud)
要么
您可以更改以下代码
if categories.contains { $0 == 1 } {
// 1 is found
}
Run Code Online (Sandbox Code Playgroud)
至
if categories.contains { ($0 as! Int) == 1 } {
// 1 is found
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您的category数组包含类型以外的其他元素,则此方法可能会导致您的应用程序崩溃Int
感谢您的评论让我检查了数组的声明,问题是在[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)