我有一个函数,它返回一个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
我该如何解决这个问题?
答案 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
}
过滤代码应按原样运行。