Ios 获取图像数组时发生indexout of range错误

Ios 获取图像数组时发生indexout of range错误,ios,arrays,swift,alamofire,Ios,Arrays,Swift,Alamofire,您好,我从响应中获取图像数组,但我获取整个数组,但有时我获取1个图像,有时获取5个图像,所以当我填充图像视图时,我获取索引超出范围错误,让我显示您的响应 模型类 响应 [RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_servi

您好,我从响应中获取图像数组,但我获取整个数组,但有时我获取1个图像,有时获取5个图像,所以当我填充图像视图时,我获取索引超出范围错误,让我显示您的响应

模型类

响应

[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"]))]



[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"])), RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "dsds", property_id: "22", regulation_item: "8", locations: "asdsad", id: "65", boiler_service_date: "", action: "Maintenance Attention Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5aQueNfpUp1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_8dlP5RlUqS1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_fqqqC9zfe91548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_sjkjOy73Y11548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_t7ePWkHif71548247477.png"]))]
var preInspData = [PreviousInspListModel]()

func previousInspAPI(){
    let preferences = UserDefaults.standard
    let uid = "u_id"
    let acTkn = "acc_tkn"

    let u_ID = preferences.object(forKey: uid)
    let A_Token = preferences.object(forKey: acTkn)

    let params = ["user_id": u_ID!, "access_token": A_Token!,"property_id": propertyID!]
    print(params)
    SVProgressHUD.show()
    Alamofire.request(previousinspectionslist, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
        switch response.result{
        case.success(let value):
            let json  = JSON(value)
            print(json)
            let data = json["data"]

            data.array?.forEach({ (iList) in
                let i_List = PreviousInspListModel(resolved: iList["resolved"].stringValue, type: iList["type"].stringValue, notes: iList["notes"].stringValue, property_id: iList["property_id"].stringValue, regulation_item: iList["regulation_item"].stringValue, locations: iList["locations"].stringValue, id: iList["id"].stringValue, boiler_service_date: iList["boiler_service_date"].stringValue, action: iList["action"].stringValue, intervention_required: iList["intervention_required"].stringValue, regulation_id: iList["regulation_id"].stringValue, regulation_item_name: iList["regulation_item_name"].stringValue, contravention: iList["contravention"].stringValue, contraventions_item_name: iList["contraventions_item_name"].stringValue, imagesArray: iList["images"].arrayObject as? [String])
                self.preInspData.append(i_List)
                print(self.preInspData)
            })
            self.tblListView.reloadData()
            SVProgressHUD.dismiss()
        case.failure(let error):
            print(error.localizedDescription)
        }

    })
}

   func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return preInspData.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! PreviousInspectionsTableViewCell
        cell.lblItem.text = preInspData[indexPath.row].regulation_item_name
        cell.lblContrevation.text = preInspData[indexPath.row].contraventions_item_name
        cell.lblLocation.text = preInspData[indexPath.row].locations
        cell.lblAction.text = preInspData[indexPath.row].action
        cell.lblNotes.text = preInspData[indexPath.row].notes
        cell.lblStatus.text = preInspData[indexPath.row].intervention_required

        let images = preInspData[indexPath.row].imagesArray

        let image1 = images![0]
        if image1 != ""{
            let imageUrl = URL(string: image1)!
            cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image2 = images![1]
        if image2 != ""{
            let imageUrl = URL(string: image2)!
            cell.img2.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image3 = images![2]
        if image3 != ""{
            let imageUrl = URL(string: image3)!
            cell.img3.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image4 = images![3]
        if image4 != ""{
            let imageUrl = URL(string: image4)!
            cell.img4.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image5 = images![4]
        if image5 != ""{
            let imageUrl = URL(string: image5)!
            cell.img5.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        cell.selectionStyle = .none
        return cell
    }
当我向你们展示第一个响应时,我只得到一张图片,在第二张中我得到了5张图片,现在我将向你们展示我的代码

代码

[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"]))]



[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"])), RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "dsds", property_id: "22", regulation_item: "8", locations: "asdsad", id: "65", boiler_service_date: "", action: "Maintenance Attention Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5aQueNfpUp1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_8dlP5RlUqS1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_fqqqC9zfe91548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_sjkjOy73Y11548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_t7ePWkHif71548247477.png"]))]
var preInspData = [PreviousInspListModel]()

func previousInspAPI(){
    let preferences = UserDefaults.standard
    let uid = "u_id"
    let acTkn = "acc_tkn"

    let u_ID = preferences.object(forKey: uid)
    let A_Token = preferences.object(forKey: acTkn)

    let params = ["user_id": u_ID!, "access_token": A_Token!,"property_id": propertyID!]
    print(params)
    SVProgressHUD.show()
    Alamofire.request(previousinspectionslist, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
        switch response.result{
        case.success(let value):
            let json  = JSON(value)
            print(json)
            let data = json["data"]

            data.array?.forEach({ (iList) in
                let i_List = PreviousInspListModel(resolved: iList["resolved"].stringValue, type: iList["type"].stringValue, notes: iList["notes"].stringValue, property_id: iList["property_id"].stringValue, regulation_item: iList["regulation_item"].stringValue, locations: iList["locations"].stringValue, id: iList["id"].stringValue, boiler_service_date: iList["boiler_service_date"].stringValue, action: iList["action"].stringValue, intervention_required: iList["intervention_required"].stringValue, regulation_id: iList["regulation_id"].stringValue, regulation_item_name: iList["regulation_item_name"].stringValue, contravention: iList["contravention"].stringValue, contraventions_item_name: iList["contraventions_item_name"].stringValue, imagesArray: iList["images"].arrayObject as? [String])
                self.preInspData.append(i_List)
                print(self.preInspData)
            })
            self.tblListView.reloadData()
            SVProgressHUD.dismiss()
        case.failure(let error):
            print(error.localizedDescription)
        }

    })
}

   func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return preInspData.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! PreviousInspectionsTableViewCell
        cell.lblItem.text = preInspData[indexPath.row].regulation_item_name
        cell.lblContrevation.text = preInspData[indexPath.row].contraventions_item_name
        cell.lblLocation.text = preInspData[indexPath.row].locations
        cell.lblAction.text = preInspData[indexPath.row].action
        cell.lblNotes.text = preInspData[indexPath.row].notes
        cell.lblStatus.text = preInspData[indexPath.row].intervention_required

        let images = preInspData[indexPath.row].imagesArray

        let image1 = images![0]
        if image1 != ""{
            let imageUrl = URL(string: image1)!
            cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image2 = images![1]
        if image2 != ""{
            let imageUrl = URL(string: image2)!
            cell.img2.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image3 = images![2]
        if image3 != ""{
            let imageUrl = URL(string: image3)!
            cell.img3.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image4 = images![3]
        if image4 != ""{
            let imageUrl = URL(string: image4)!
            cell.img4.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image5 = images![4]
        if image5 != ""{
            let imageUrl = URL(string: image5)!
            cell.img5.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        cell.selectionStyle = .none
        return cell
    }

现在,如果数组中只有一个图像,那么我将获取索引超出范围错误,因此如何处理此问题,请帮助我。问题是如何从索引不存在的数组中获取元素。i、 e索引超出范围

[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"]))]



[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"])), RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "dsds", property_id: "22", regulation_item: "8", locations: "asdsad", id: "65", boiler_service_date: "", action: "Maintenance Attention Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5aQueNfpUp1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_8dlP5RlUqS1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_fqqqC9zfe91548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_sjkjOy73Y11548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_t7ePWkHif71548247477.png"]))]
var preInspData = [PreviousInspListModel]()

func previousInspAPI(){
    let preferences = UserDefaults.standard
    let uid = "u_id"
    let acTkn = "acc_tkn"

    let u_ID = preferences.object(forKey: uid)
    let A_Token = preferences.object(forKey: acTkn)

    let params = ["user_id": u_ID!, "access_token": A_Token!,"property_id": propertyID!]
    print(params)
    SVProgressHUD.show()
    Alamofire.request(previousinspectionslist, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
        switch response.result{
        case.success(let value):
            let json  = JSON(value)
            print(json)
            let data = json["data"]

            data.array?.forEach({ (iList) in
                let i_List = PreviousInspListModel(resolved: iList["resolved"].stringValue, type: iList["type"].stringValue, notes: iList["notes"].stringValue, property_id: iList["property_id"].stringValue, regulation_item: iList["regulation_item"].stringValue, locations: iList["locations"].stringValue, id: iList["id"].stringValue, boiler_service_date: iList["boiler_service_date"].stringValue, action: iList["action"].stringValue, intervention_required: iList["intervention_required"].stringValue, regulation_id: iList["regulation_id"].stringValue, regulation_item_name: iList["regulation_item_name"].stringValue, contravention: iList["contravention"].stringValue, contraventions_item_name: iList["contraventions_item_name"].stringValue, imagesArray: iList["images"].arrayObject as? [String])
                self.preInspData.append(i_List)
                print(self.preInspData)
            })
            self.tblListView.reloadData()
            SVProgressHUD.dismiss()
        case.failure(let error):
            print(error.localizedDescription)
        }

    })
}

   func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return preInspData.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! PreviousInspectionsTableViewCell
        cell.lblItem.text = preInspData[indexPath.row].regulation_item_name
        cell.lblContrevation.text = preInspData[indexPath.row].contraventions_item_name
        cell.lblLocation.text = preInspData[indexPath.row].locations
        cell.lblAction.text = preInspData[indexPath.row].action
        cell.lblNotes.text = preInspData[indexPath.row].notes
        cell.lblStatus.text = preInspData[indexPath.row].intervention_required

        let images = preInspData[indexPath.row].imagesArray

        let image1 = images![0]
        if image1 != ""{
            let imageUrl = URL(string: image1)!
            cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image2 = images![1]
        if image2 != ""{
            let imageUrl = URL(string: image2)!
            cell.img2.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image3 = images![2]
        if image3 != ""{
            let imageUrl = URL(string: image3)!
            cell.img3.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image4 = images![3]
        if image4 != ""{
            let imageUrl = URL(string: image4)!
            cell.img4.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image5 = images![4]
        if image5 != ""{
            let imageUrl = URL(string: image5)!
            cell.img5.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        cell.selectionStyle = .none
        return cell
    }
您的行代码单元格出现问题:

let image1 = images![0]
if image1 != ""{
    let imageUrl = URL(string: image1)!
    cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}
 extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}
此问题的解决方案是通过添加此扩展方法来处理索引超出范围错误:

let image1 = images![0]
if image1 != ""{
    let imageUrl = URL(string: image1)!
    cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}
 extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}
用法:

let image1 = images![0]
if image1 != ""{
    let imageUrl = URL(string: image1)!
    cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}
 extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}

问题在于从索引不存在的数组中获取元素。i、 e索引超出范围

[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"]))]



[RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "TEst", property_id: "22", regulation_item: "8", locations: "Test", id: "64", boiler_service_date: "", action: "Further Investigation / Maintenance Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5fzy77gNL31548237434.png"])), RentComply.PreviousInspListModel(resolved: "N/A", type: "Internal", notes: "dsds", property_id: "22", regulation_item: "8", locations: "asdsad", id: "65", boiler_service_date: "", action: "Maintenance Attention Required", intervention_required: "N/A", regulation_id: "4", regulation_item_name: "Floors", contravention: "27", contraventions_item_name: "Damaged wooden floors", imagesArray: Optional(["http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_5aQueNfpUp1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_8dlP5RlUqS1548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_fqqqC9zfe91548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_sjkjOy73Y11548247477.png", "http://christies.buildingcontrolregister.ie/webservice/assets/uploads/inspection_photo/img_t7ePWkHif71548247477.png"]))]
var preInspData = [PreviousInspListModel]()

func previousInspAPI(){
    let preferences = UserDefaults.standard
    let uid = "u_id"
    let acTkn = "acc_tkn"

    let u_ID = preferences.object(forKey: uid)
    let A_Token = preferences.object(forKey: acTkn)

    let params = ["user_id": u_ID!, "access_token": A_Token!,"property_id": propertyID!]
    print(params)
    SVProgressHUD.show()
    Alamofire.request(previousinspectionslist, method: .post, parameters: params).responseJSON(completionHandler: {(response) in
        switch response.result{
        case.success(let value):
            let json  = JSON(value)
            print(json)
            let data = json["data"]

            data.array?.forEach({ (iList) in
                let i_List = PreviousInspListModel(resolved: iList["resolved"].stringValue, type: iList["type"].stringValue, notes: iList["notes"].stringValue, property_id: iList["property_id"].stringValue, regulation_item: iList["regulation_item"].stringValue, locations: iList["locations"].stringValue, id: iList["id"].stringValue, boiler_service_date: iList["boiler_service_date"].stringValue, action: iList["action"].stringValue, intervention_required: iList["intervention_required"].stringValue, regulation_id: iList["regulation_id"].stringValue, regulation_item_name: iList["regulation_item_name"].stringValue, contravention: iList["contravention"].stringValue, contraventions_item_name: iList["contraventions_item_name"].stringValue, imagesArray: iList["images"].arrayObject as? [String])
                self.preInspData.append(i_List)
                print(self.preInspData)
            })
            self.tblListView.reloadData()
            SVProgressHUD.dismiss()
        case.failure(let error):
            print(error.localizedDescription)
        }

    })
}

   func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return preInspData.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! PreviousInspectionsTableViewCell
        cell.lblItem.text = preInspData[indexPath.row].regulation_item_name
        cell.lblContrevation.text = preInspData[indexPath.row].contraventions_item_name
        cell.lblLocation.text = preInspData[indexPath.row].locations
        cell.lblAction.text = preInspData[indexPath.row].action
        cell.lblNotes.text = preInspData[indexPath.row].notes
        cell.lblStatus.text = preInspData[indexPath.row].intervention_required

        let images = preInspData[indexPath.row].imagesArray

        let image1 = images![0]
        if image1 != ""{
            let imageUrl = URL(string: image1)!
            cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image2 = images![1]
        if image2 != ""{
            let imageUrl = URL(string: image2)!
            cell.img2.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image3 = images![2]
        if image3 != ""{
            let imageUrl = URL(string: image3)!
            cell.img3.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image4 = images![3]
        if image4 != ""{
            let imageUrl = URL(string: image4)!
            cell.img4.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        let image5 = images![4]
        if image5 != ""{
            let imageUrl = URL(string: image5)!
            cell.img5.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
        }

        cell.selectionStyle = .none
        return cell
    }
您的行代码单元格出现问题:

let image1 = images![0]
if image1 != ""{
    let imageUrl = URL(string: image1)!
    cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}
 extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}
此问题的解决方案是通过添加此扩展方法来处理索引超出范围错误:

let image1 = images![0]
if image1 != ""{
    let imageUrl = URL(string: image1)!
    cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}
 extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}
用法:

let image1 = images![0]
if image1 != ""{
    let imageUrl = URL(string: image1)!
    cell.img1.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "logo_grey"), options: .refreshCached, completed: nil)
}
 extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Iterator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Array {
    subscript (safe index: Int) -> Element? {
        return indices ~= index ? self[index] : nil
    }
}

到底是哪一行代码导致了错误?意味着如果我在数组中得到5个图像,那么我不会得到错误,但是如果我只得到一个图像,那么我会在
let image2=images处得到错误![1] 如果图像2!=“{let imageUrl=URL(字符串:image2)!cell.img2.sd_setImage(带:imageUrl,占位符image:UIImage(名为:“logo_grey”),选项:.refreshCached,completed:nil)}
代码行的preInspData是什么
let images=preInspData[indexPath.row].imagesArray
?这是我的模型类数组等待我将用模型类更新问题如果不能保证数组中有那么多元素,不要编写假定数组中有特定数量元素的代码。到底是哪行代码导致了错误?意味着如果我在数组中得到5个图像,那么我不会得到错误,但如果我得到了错误仅获取一个图像时,我在
let image2=images处遇到错误![1] 如果图像2!=“{let imageUrl=URL(字符串:image2)!cell.img2.sd_setImage(带:imageUrl,占位符image:UIImage(名为:“logo_grey”),选项:.refreshCached,completed:nil)}
代码行的preInspData是什么
let images=preInspData[indexPath.row].imagesArray
?这是我的模型类数组,请稍候,我将用模型类更新问题。如果不能保证数组中有那么多元素,请不要编写假定数组中有特定数量元素的代码。@vishal您将得到一个nil值,这样您就可以处理索引超出范围的错误。我认为这将帮助您解决这个问题。@vishal您将得到一个nil值,这样您就可以处理索引超出范围的错误。我想这会帮助你解决这个问题。