Daisy R.
Daisy R.

Reputation: 633

Cannot Assign a value of type [AnyObject] tp a value of type NSMutableArray

I am trying to get the result of a search using NSPredicate however it conflicts when I try to use filteredArrayUsingPredicate since it returns AnyObject. I've commented out the method I attempted since it's not returning the proper results.

var contacts: NSMutableArray = []
var filteredContacts: NSMutableArray = []

func newFilteringPredicateWithText(text: String) -> NSPredicate {
    return NSPredicate(format:"SELF contains[cd] %@", text);
}
func contactPickerTextViewDidChange(textViewText: String!) {

    if (textViewText == "") {
        self.filteredContacts = self.contacts;
    }
    else {
        var predicate: NSPredicate = self.newFilteringPredicateWithText(textViewText)
        self.filteredContacts = self.contacts.filteredArrayUsingPredicate(predicate)
        //var temp = NSMutableArray(array: self.contacts.filteredArrayUsingPredicate(predicate))
        //self.filteredContacts = temp
    }
    self.tableView.reloadData()
}

Upvotes: 0

Views: 677

Answers (1)

vadian
vadian

Reputation: 285069

NSMutableArray and AnyObject are not related therefore you can't easily downcast the type.

I'd suggest a native Swift solution

var contacts: Array<String> = []
var filteredContacts: Array<String> = []

func contactPickerTextViewDidChange(textViewText: String!) {

  if textViewText.isEmpty {
    filteredContacts = contacts
  }
  else {
    filteredContacts = contacts.filter {$0.rangeOfString(textViewText, options: [.CaseInsensitiveSearch, .DiacriticInsensitiveSearch]) != nil }
  }
  tableView.reloadData()
}

Upvotes: 2

Related Questions