我试图通过对象数组的属性之一来过滤它。尝试了很多解决方案,但在我开始输入后抛出错误
//我的模型类
class Book{
var bookId:Int?
var bookName:String?
//omitted init function
}
// View Controller //这是我的文本字段委托(delegate)方法
let myArray:[Book] = [Book(bookId:23,bookName:"book1"),Book(bookId:53,bookName:"book2"),Book(bookId:43,bookName:"book3"),]
func textField(_ textField: UITextField, shouldChangeCharactersIn
range: NSRange, replacementString string: String) -> Bool
{
lastCharactar = string
textFieldText = myTextField.text! + lastCharactar
let predicate = NSPredicate(format: "ANY SELF.bookName BEGINSWITH %@", textFieldText)
let arr = ( myArray as NSArray).filtered(using: predicate)
return true
}
I am getting the following error
"this class is not key value coding-compliant for the key bookName."
最佳答案
Swift Array 不需要谓词来过滤其内容。 Swift 数组有 filter 方法来过滤数组。例如:
struct Book{
var bookId:Int?
var bookName:String?
}
let myArray:[Book] = [Book(bookId:23,bookName:"book1"),Book(bookId:53,bookName:"book2"),Book(bookId:43,bookName:"book3"),]
func textField(_ textField: UITextField, shouldChangeCharactersIn
range: NSRange, replacementString string: String) -> Bool
{
lastCharactar = string
textFieldText = myTextField.text! + lastCharactar
let arr = myArray.filter { (book) -> Bool in
if let name = book.bookName, name.hasPrefix(textFieldText) {
return true
}
return false
}
return true
}
注意:结构是一种值类型,当将其分配给变量或常量或传递给函数时,其值会被复制,而类是引用类型,默认情况下不会复制其值。
关于swift - 无法过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57655615/