我正在尝试将文本字段用作表视图的搜索栏。所以我添加了下面的代码。现在,它显示了一些错误,例如
Cannot assign value of type 'Array<Dictionary<String, String>>' to type '[MyVC.Objects]'
var objectArray = [Objects]()
var SearchedobjectArray = [Objects]()
override func viewDidLoad() {
super.viewDidLoad()
SearchedobjectArray = objectArray
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if string.isEmpty
{
search = String(search.characters.dropLast())
}
else
{
search=textField.text!+string
}
print(search)
let predicate=NSPredicate(format: "SELF.name CONTAINS[cd] %@", search)
let arr=(objectArray as NSArray).filtered(using: predicate)
if arr.count > 0
{
SearchedobjectArray.removeAll(keepingCapacity: true)
SearchedobjectArray = arr as! Array<Dictionary<String,String>>
}
else
{
SearchedobjectArray=objectArray
}
looTable.reloadData()
return true
}
错误在这里:
SearchedobjectArray = arr as! Array<Dictionary<String,String>>
我知道,我不用作Array<Dictionary<String,String>
。但是在这里我不确定如何像我的注射一样追加。
有什么帮助吗?
答案 0 :(得分:0)
快速修复:
SearchedobjectArray = arr as! [Objects]
您的数组不是由字典组成的。
实际修复:
忘记NSArray
和NSPredicate
并使用快速过滤:
SearchedobjectArray = objectArray.filter {
$0.name.range(of: search, options: [.diacriticInsensitive, .caseInsensitive]) != nil
}
if SearchedobjectArray.isEmpty {
SearchedobjectArray = objectArray
}