如果找不到结果,对象过滤器会崩溃 [英] Object filter crashes if no results can be found

查看:45
本文介绍了如果找不到结果,对象过滤器会崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些代码来从自定义对象数组中查找用户的收藏夹.除非该对象不存在,否则它绝对可以正常工作,在这种情况下它只会崩溃.我正在考虑以不同的方式完全重写代码,但我想可能有一种方法可以修复它......我只是不知道如何.

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.

这是我的代码:

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

就像我说的,如果可以找到 favouritesArray 中的字符串,它就可以正常工作,但如果找不到,它就会崩溃.

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?

谢谢!

推荐答案

您需要检查 result 的长度 - 您可以通过替换来做到这一点

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

return result[0]

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

这篇关于如果找不到结果,对象过滤器会崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆