在Swift中将AnyObject添加到NSMutableArray

Sal*_*h Ç 0 uitableview nspredicate ios swift

我只是想做Tableview搜索.我正在NSPredicate用于搜索.

每个教程都会给出这个代码行:

let resultPredicate = NSPredicate(format: "SELF contains[c] %@", searchText)
self.nameArray = self.nameArray.filteredArrayUsingPredicate(resultPredicate)
Run Code Online (Sandbox Code Playgroud)

但在第二行Xcode中说: Cannot assign a value of type '[AnyObject]' to a value of type 'NSMutableArray'

我试图转换,但这次xcode创建零值.我的两个阵列都是NSMutableArray.任何建议?

编辑

我的手机代码:

let cell:ItemsTVCell = tableView.dequeueReusableCellWithIdentifier("CELL") as! ItemsTVCell

    if tableView == self.searchDisplayController?.searchResultsTableView {
        cell.itemNameLabel.text = filteredArray[indexPath.row] as? String
    } else {
        cell.itemNameLabel.text = nameArray[indexPath.row] as? String
    }

    return cell
Run Code Online (Sandbox Code Playgroud)

rud*_*udd 5

filteredArrayUsingPredicate返回[AnyObject],看起来您的属性类型为NSMutableArray.根据偏好,您有几个选择:

  • 将您的属性更改为Swift数组(例如var nameArray: [String])而不是NSMutableArray.而不是使用filteredArrayUsingPredicate,只需使用数组的过滤方法:

    self.nameArray = self.nameArray.filter({contains($0.lowercaseString, searchText.lowercaseString})

  • 如果必须继续将属性保留为NSMutableArray,则可以使用已过滤数组的内容创建NSArray实例:

    NSMutableArray(array: self.nameArray.filteredArrayUsingPredicate(resultPredicate))