无法将AnyObject类型的值赋给String类型的值

时间:2015-10-08 11:43:43

标签: ios swift uisearchbar uisearchdisplaycontroller

我有一个函数,它返回一个AnyObject数组:

public func xmppRosterDidEndPopulating(sender: XMPPRoster?) {
    let jidList = OneChat.sharedInstance.xmppRosterStorage.jidsForXMPPStream(OneChat.sharedInstance.xmppStream)

    contacts = jidList      
}

我有一个数组:var contacts = [AnyObject]()

稍后,我想在这些值中运行我的搜索功能:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    filtered = contacts.filter({ (text) -> Bool in
        let tmp: NSString = text as! NSString
        let range = tmp.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
        return range.location != NSNotFound
    })
    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.tableView.reloadData()
}

但它返回错误:

Cannot assign a value of type AnyObject to a value of type String

filtered = contacts.filter({ (text) -> Bool in

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

filter方法返回与输入相同类型的数组。在这种情况下,由于contacts[AnyObject],它将返回[AnyObject]

如果您只处理字符串,那么最好的方法是更改​​contacts的声明来表示字符串并转换jidList以提供字符串数组...

if let jidList = OneChat.sharedInstance.xmppRosterStorage.jidsForXMPPStream(OneChat.sharedInstance.xmppStream) as? [String] {
    contacts = jidList
} else {
    // handle failure to convert to string array
}

过滤代码应按原样运行。