Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/114.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如果找不到结果,对象筛选器将崩溃_Ios_Swift_Uitableview_Nsarray_Nsobject - Fatal编程技术网

Ios 如果找不到结果,对象筛选器将崩溃

Ios 如果找不到结果,对象筛选器将崩溃,ios,swift,uitableview,nsarray,nsobject,Ios,Swift,Uitableview,Nsarray,Nsobject,我已经编写了一些代码来从自定义对象数组中查找用户最喜欢的对象。除非该对象不存在,否则它绝对可以正常工作,在这种情况下,它只是崩溃。我正在考虑用另一种方式完全重写代码,但我想可能有一种方法可以修复它。。。我就是不知道怎么做 这是我的密码: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell

我已经编写了一些代码来从自定义对象数组中查找用户最喜欢的对象。除非该对象不存在,否则它绝对可以正常工作,在这种情况下,它只是崩溃。我正在考虑用另一种方式完全重写代码,但我想可能有一种方法可以修复它。。。我就是不知道怎么做

这是我的密码:

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]
}
就像我说的,如果可以找到FavoriteSarray中的字符串,那么它工作得很好,但是如果找不到,它就会崩溃

有人能建议我可以做些什么改变来阻止崩溃,让它返回零吗


谢谢

您需要检查
结果
的长度-您可以通过替换

return result[0]


您需要检查
结果
的长度-您可以通过替换

return result[0]


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

return result.first
返回一个可选的。不过,更好的选择是使用
indexOf()
函数(如果您使用的是Swift 2),因为它不会构建整个数组,一旦找到您要查找的内容,就会停止查看RiderRay的其余部分:

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

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

return result.first
返回一个可选的。不过,更好的选择是使用
indexOf()
函数(如果您使用的是Swift 2),因为它不会构建整个数组,一旦找到您要查找的内容,就会停止查看RiderRay的其余部分:

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

返回结果。first
将是最快的方式:)
返回结果。first
将是最快的方式:)