swift - 无法过滤对象数组

标签 swift nspredicate

我试图通过对象数组的属性之一来过滤它。尝试了很多解决方案,但在我开始输入后抛出错误

//我的模型类

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/

相关文章:

ios - 如何将文本从 SafariViewController 快速获取到我们的应用程序?

xcode - geocoder.geocodeAddressString 今天不再适用于快速更新

ios - didUpdateLocations 方法未被调用

swift - 拍照允许我在 BSImagePicker Swift ios 中选择超过 maxNumberOfSelections

ios - 使用 NSPredicate 过滤 NSArray

ios - 排序核心数据获取(swift 4)

ios - 如何为 segue 引用 NSPredicate 的 "%@"?

ios - 旋转 SCNCamera 节点,观察一个假想球体周围的物体

ios - 使用谓词查找以 A 开头和结尾的字符串

ios - 具有多个对多条件的核心数据 NSPredicate