Object filter crashes if no results can be found

瘦欲@ 提交于 2019-12-11 09:45:03

问题


I have written some code to find a user's favourites out of an array of custom objects. It works absolutely fine unless that object does not exist, in which case it just crashes. I was considering completely rewriting the code a different way, but I imagine there is probably a way to fix it... I just can't figure out how.

Here is my code:

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]
}

Like I say, it works fine if the Strings in favouritesArray can be found, however it crashes if not.

Can anyone suggest what changes I could make to stop the crash, and to just get it to return nil?

Thanks!


回答1:


You need to check result's length - you can do so by replacing

return result[0]

with

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



回答2:


You can use the first property on the filtered array:

return result.first

which returns an optional. A better option, though, is to use the indexOf() function (if you're in Swift 2), as it doesn't build an entire array, and stops looking through the rest of the rideArray once it finds what you're looking for:

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


来源:https://stackoverflow.com/questions/31440818/object-filter-crashes-if-no-results-can-be-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!