我在下面有一些代码。我有一个来自SwiftyJSON的JSON对象,我想过滤它。 很自然地,我想:让我们过滤它并使用过滤后的数据实例化一个新数组。
import UIKit
import SwiftyJSON
import Alamofire
class SchoolSelectViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate {
let url = "https://mijn.magister.net/api/schools?filter=%%%".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
var json: JSON = []
var filteredJson: JSON = []
var resultSearchController = UISearchController()
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request(.GET, self.url!).validate().responseJSON {
response in
switch response.result {
case .Success:
if let value = response.result.value {
self.json = JSON(value)
}
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.searchBar.delegate = self
self.resultSearchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = self.resultSearchController.searchBar
self.definesPresentationContext = true
self.tableView.reloadData()
break
case .Failure: break
}
}
self.navigationController?.navigationBarHidden = true
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("Called tableView cellForRowAtIndexPath")
let cell = tableView.dequeueReusableCellWithIdentifier("schoolSelectCell")! as UITableViewCell
let cellTitle = json[indexPath.row]["Name"]
let cellDetailTitle = json[indexPath.row]["Url"]
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel?.text = cellTitle.string
cell.detailTextLabel?.text = cellDetailTitle.string
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.resultSearchController.active) {
return self.filteredJson.count
} else {
return self.json.count
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchString = self.resultSearchController.searchBar.text
}
func filterContentForTextSearch(searchText: String) {
self.filteredJson = self.json[0]["Name"].arrayValue.filter({
(school: JSON) -> Bool in
})
}
}
但我结束了接收此错误:Cannot convert value of type 'JSON -> Bool' to expected argument type '(Element) -> Bool'
我该如何解决这个问题?
答案 0 :(得分:1)
你应该过滤一个数组。
使用以下内容:
self.filteredJson = self.json.arrayValue.filter({
(school: JSON) -> Bool in
// Do something.
})
如果上述代码不起作用,请检查JSON
的类型。