问题
I am trying to create a UITableView on my IOS app that displays a list of all the app's registered users from Firebase and includes a UISearchBar to search through them. I am very new to this and unfortunately this code is giving me the following error: "Value of type 'User' has no subscripts" on the line of code "let user = users[indexPath.row]"
There is an NSObject User class in another file that defines name and email as String?
These are the variables:
var searchActive : Bool!
var userList = [User]()
var filterUsers = [User]()
private var users = User()
private var hasFetched = false
Here is the search bar function I was using that is giving me the error:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filterUsers = userList.filter({ (text) -> Bool in
let temp: NSString = text.name! as NSString
let range = temp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
return range.location != NSNotFound
})
if(filterUsers.count == 0){
searchActive = false;
} else {
searchActive = true;
}
//refreshTable()
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(searchActive) {
return filterUsers.count
}
return userList.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let user = userList[indexPath.row] as? [String : AnyObject] {
}
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell;
let user = users[indexPath.row]
cell.textLabel?.text = user.name
cell.textLabel?.text = user.name
return cell;
}
} }
回答1:
Modify this:
let user = users[indexPath.row]
To this:
let user = searchActive ? filterUsers[indexPath.row] : userList[indexPath.row]
来源:https://stackoverflow.com/questions/62626172/value-of-type-user-has-no-subscripts