Swift:致命错误:索引超出范围 [英] Swift: fatal error: Index out of range

查看:235
本文介绍了Swift:致命错误:索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

填充UITableView时,我的索引超出范围。
我不知道为什么它会给我错误。我的单元格创建函数有一个条件语句,它检查每个数组的计数,然后在索引0上添加一个自定义单元格。

I'm getting an "Index out of range" when populating a UITableView. I don't know why it gives me error. I have a condition statement on my cell creation function which checks for the count of each array and then adds a custom cell on index 0.

如果有人知道这个问题,请告诉我解决方案。我已经工作了好几天了,似乎无法解决这个问题。

If anyone knows about this problem, please tell me the solution. I've been working on it for days and can't seem to figure this one out.

var homeArr: [services] = []
var autoArr: [services] = []

Alamofire.request(url_specialist_request_url, method: .post, parameters: parameters).responseJSON {
    response in

    if response.data != nil {
        let json = JSON(data: response.data!)
        let json_count = json.count

        // print(json)

        self.homeArr.append(services(service_name:"",service_icon:"",service_category:""))
        self.autoArr.append(services(service_name:"",service_icon:"",service_category:""))
        self.personalArr.append(services(service_name:"",service_icon:"",service_category:""))

        for i in 0 ..< json_count {
            let categoryId = json[i]["category_id"].string!
            if(categoryId == "1") {
                self.homeArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            } else if(categoryId == "2") {
                self.autoArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            } else {
                self.personalArr.append(services(service_name:json[i]["service_name"].string!,service_icon:"\(json[i]["service_icon"].string!)Icon",service_category:json[i]["category_id"].string!))
            }
        }

        self.tableView.reloadData()
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell

    let home_dict = self.homeArr[indexPath.row]
    // ** Index out of range on the following line **
    let auto_dict = self.autoArr[indexPath.row]

    if(self.homeArr.count > 1) {
        if (indexPath.row == 0)
        {
            cell.serviceLabel!.text = "Home"
            cell.contentView.backgroundColor = UIColor.blue
        } else {
            cell.serviceLabel!.text = home_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
        }
    }

    if(self.autoArr.count > 1) {
        if (indexPath.row == 0)
        {
            cell.serviceLabel!.text = "Personal"
            cell.contentView.backgroundColor = UIColor.blue
        } else {
            cell.serviceLabel!.text = auto_dict.service_name
            cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
        }
    }

    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return(homeArr.count + arrAuto.count)
}

这就是我想要实现的目标

This is what I want to achieve

    Home Arr cell
    Home Arr cell

  • value1

  • value2
    • 自动Arr单元格

  • value1

  • value2
  • 推荐答案

    创建两个部分一个用于HomeArr,另一个用于AutoArr。我相信每个部分你想展示一个带有一些标题的附加单元格。所以下面的代码可以帮助你。

    Create two sections One for HomeArr and one for AutoArr. I believe for each section you wanna show a additional cell with some title. So below code should help you.

    extension ViewController : UITableViewDataSource {
        func numberOfSections(in tableView: UITableView) -> Int {
            return 2
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            if section == 0 {
                return (homeArr.count > 0) ?  homeArr.count + 1 : 0
            }
            else {
                return (autoArr.count > 0) ?  autoArr.count + 1 : 0
            }
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell
            if indexPath.section == 0 {
                if (indexPath.row == 0)
                {
                    cell.serviceLabel!.text = "Home"
                    cell.contentView.backgroundColor = UIColor.blue
                } else {
                    let home_dict = self.homeArr[indexPath.row - 1]
                    cell.serviceLabel!.text = home_dict.service_name
                    cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
                }
            }
            else {
                if (indexPath.row == 0)
                {
                    cell.serviceLabel!.text = "Personal"
                    cell.contentView.backgroundColor = UIColor.blue
                } else {
                    let auto_dict = self.autoArr[indexPath.row - 1]
                    cell.serviceLabel!.text = auto_dict.service_name
                    cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
                }
            }
            return cell
        }
    }
    

    编辑:

    正如 rmaddy 在下面的评论中


    为什么每个部分都有额外的行?为什么不使用节标题

    Why the extra row in each section? Why not use a section header instead?

    因为我们不知道OP的确切要求我将我的代码更新为显示部分标题。

    As we are not aware of OP's exact requirement I am updating my code to show section title as well.

     extension ViewController : UITableViewDataSource {
        func numberOfSections(in tableView: UITableView) -> Int {
            return 2
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            if section == 0 {
                return homeArr.count
            }
            else {
                return autoArr.count
            }
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCell",for:indexPath) as! servicesCell
            if indexPath.section == 0 {
                let home_dict = self.homeArr[indexPath.row]
                cell.serviceLabel!.text = home_dict.service_name
                cell.serviceIcon!.image = UIImage(named:"\(home_dict.service_icon)")
            }
            else {
                let auto_dict = self.autoArr[indexPath.row]
                cell.serviceLabel!.text = auto_dict.service_name
                cell.serviceIcon!.image = UIImage(named:"\(auto_dict.service_icon)")
            }
            return cell
        }
    
        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            if section == 0 {
                return "Home Arr cell"
            }
            else {
                return "Auto Arr cell"
            }
        }
    }
    

    这篇关于Swift:致命错误:索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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