Swift:致命错误:索引超出范围

时间:2017-11-17 16:46:04

标签: ios arrays swift indexing

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

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

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

这就是我想要实现的目标

    Home Arr cell

  • 值1
  • 值2
    • 自动Arr单元格

  • 值1
  • 值2
  • 1 个答案:

    答案 0 :(得分:1)

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

    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在下面的评论中所指出的

      

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

    由于我们不知道OP的确切要求,我正在更新我的代码以显示部分标题。

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