如果没有find结果,则对象筛选器将崩溃

我已经写了一些代码来查找用户的自定义对象数组中的collections夹。 它工作绝对正常,除非该对象不存在,在这种情况下,它只是崩溃。 我正在考虑以不同的方式完全重写代码,但我想可能有一种方法来解决它…我只是不知道如何。

这是我的代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("rideCell", forIndexPath: indexPath) as! RideCell var ride = DataManager.sharedInstance.getRideByName(favouritesArray[indexPath.row] as! String) if ride != nil { cell.rideNameLabel.text = ride!.name var dateFormat = NSDateFormatter() dateFormat.dateFormat = "h:mm a" cell.updatedLabel.text = dateFormat.stringFromDate(ride!.updated!) if ride!.waitTime! == "Closed" { cell.waitTimeLabel.text = ride!.waitTime! } else { cell.waitTimeLabel.text = "\(ride!.waitTime!)m" } } return cell } func getRideByName(name: String) -> Ride? { let result = self.rideArray.filter({ $0.name == name }) return result[0] } 

就像我说的,如果可以findfavouritesArray中的string,它就可以正常工作,但是如果没有的话,它就会崩溃。

任何人都可以提出什么样的改变,我可以制止崩溃,并得到它返回零?

谢谢!

你需要检查result的长度 – 你可以通过更换

 return result[0] 

 return result.count == 0 ? nil : result[0] 

您可以使用已过滤数组的first属性:

 return result.first 

它返回一个可选项。 但是,更好的select是使用indexOf()函数(如果你在Swift 2中),因为它不会构build一个完整的数组,并且只要find你想要的就停止查看rideArray的其余部分寻找:

 return self.rideArray.indexOf { $0.name == name }.map { self.rideArray[$0] }