2017-12-11 23 views
-1

나는 contrl 세그먼트와 UITableview 있습니다. 선택한 세그먼트 또는 수행 된 검색에 따라 테이블이 다시로드됩니다. 컨트롤 세그먼트가 정상적으로 작동하지만 검색이 작동하지 않습니다. 바에 아무 것도 입력하지 않으면 리로드 만되고 셀을 클릭하면 충돌이 발생합니다. 누군가 나를 도와 줄 수 있습니까? 정말 감사합니다치명적인 오류 : 색인 범위를 벗어난 항목 검색

var auxiliar: [Shops]? = [Shops]() 
    var searchActive: Bool = false  
// shops category 
    var restuarnt = [Shops]() 
    var coffee = [Shops]() 
    var pharmacy = [Shops]() 
    var supermarket = [Shops]() 
    var home = [Shops]() 
    var clothes = [Shops]() 
    var allShops = [Shops]()  
    var shops = [Shops]() 

    var selectedIndex = 0 



s.valueChange = { index in 

      if index == 0 { 

       self.selectedIndex = 0 
       self.tableView.reloadData() 

      } 
      if index == 1 { 
       self.selectedIndex = 1 

       self.tableView.reloadData() 
      } 

      if index == 2 { 
       self.selectedIndex = 2 

      } 
      if index == 3 { 

       self.selectedIndex = 3 

      } 



func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     if selectedIndex == 0 { 
      return allShops.count 

     } 
     if selectedIndex == 1 { 

      return self.coffee.count 
     } 
     if selectedIndex == 2 { 

      return self.restuarnt.count 
     } 
     if selectedIndex == 3 { 

      return self.pharmacy.count 
     } 

     if searchActive { 
      return auxiliar!.count 
     }else{ 
      return allShops.count 

     } 

    } 


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 


    if selectedIndex == 0 { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell 

     let entry = shops[indexPath.row] 

     cell.shopImage.hnk_setImage(from: URL(string: entry.Logo)) 
     cell.shopName.text = entry.shopname 
     cell.star.rating = Double(entry.rate) 
     cell.time.text = entry.time 


     cell.backgroundColor = UIColor(white: 1 , alpha : 0.5) 
     return cell 
    } 

    if selectedIndex == 1 { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell 

     let entry = coffee[indexPath.row] 

     cell.shopImage.hnk_setImage(from: URL(string: entry.Logo)) 
     cell.shopName.text = entry.shopname 
     cell.star.rating = Double(entry.rate) 
     cell.time.text = entry.time 


     cell.backgroundColor = UIColor(white: 1 , alpha : 0.5) 
     return cell 
    } 

    if selectedIndex == 2 { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell 

     let entry = restuarnt[indexPath.row] 

     cell.shopImage.hnk_setImage(from: URL(string: entry.Logo)) 
     cell.shopName.text = entry.shopname 
     cell.star.rating = Double(entry.rate) 
     cell.time.text = entry.time 


     cell.backgroundColor = UIColor(white: 1 , alpha : 0.5) 
     return cell 
    } 
    if selectedIndex == 3 { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell 

     let entry = pharmacy[indexPath.row] 

     cell.shopImage.hnk_setImage(from: URL(string: entry.Logo)) 
     cell.shopName.text = entry.shopname 
     cell.star.rating = Double(entry.rate) 
     cell.time.text = entry.time 


     cell.backgroundColor = UIColor(white: 1 , alpha : 0.5) 
     return cell 
    } 

    if searchActive 

    { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell 
     let entry1 = auxiliar?[indexPath.row] 


     cell.shopImage.hnk_setImage(from: URL(string: (entry1?.Logo)!)) 
     cell.shopName.text = entry1?.shopname 

     cell.backgroundColor = UIColor(white: 1 , alpha : 0.5) 
     cell.time.text = entry1?.time 

     cell.star.rating = Double((entry1?.rate)!) 
     return cell 
    } 
    else { 


     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell 

     let entry = shops[indexPath.row] 

     cell.shopImage.hnk_setImage(from: URL(string: entry.Logo)) 
     cell.shopName.text = entry.shopname 
     cell.star.rating = Double(entry.rate) 
     cell.time.text = entry.time 


     cell.backgroundColor = UIColor(white: 1 , alpha : 0.5) 
     return cell 

    } 
} 



func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
     tableView.deselectRow(at: indexPath, animated: true) 
     if selectedIndex == 1 { 
      let meal1 = coffee[indexPath.row] 


      guard (coffee.count) > indexPath.row else { 
       print("Index out of range") 
       return 
      } 

      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! MealsDetailsController 
      viewController.passedValue = (meal1.familiy_id) 
      viewController.name = (meal1.shopname) 

      print("\(meal1.familiy_id) im the search ") 
      view.animateRandom() 
      self.present(viewController, animated: true , completion: nil) 



     } 
     if selectedIndex == 0 { 
      let meal1 = shops[indexPath.row] 


      guard (shops.count) > indexPath.row else { 
       print("Index out of range") 
       return 
      } 

      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! MealsDetailsController 
      viewController.passedValue = (meal1.familiy_id) 
      viewController.name = (meal1.shopname) 

      print("\(meal1.familiy_id) im the search ") 
      view.animateRandom() 
      self.present(viewController, animated: true , completion: nil) 



     } 
     if selectedIndex == 2 { 
      let meal1 = restuarnt[indexPath.row] 


      guard (restuarnt.count) > indexPath.row else { 
       print("Index out of range") 
       return 
      } 

      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! MealsDetailsController 
      viewController.passedValue = (meal1.familiy_id) 
      viewController.name = (meal1.shopname) 

      print("\(meal1.familiy_id) im the search ") 
      view.animateRandom() 
      self.present(viewController, animated: true , completion: nil) 



     } 
     if selectedIndex == 3 { 
      let meal1 = pharmacy[indexPath.row] 


      guard (pharmacy.count) > indexPath.row else { 
       print("Index out of range") 
       return 
      } 

      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! MealsDetailsController 
      viewController.passedValue = (meal1.familiy_id) 
      viewController.name = (meal1.shopname) 

      print("\(meal1.familiy_id) im the search ") 
      view.animateRandom() 
      self.present(viewController, animated: true , completion: nil) 



     } 

     if searchActive { 
      let meal1 = auxiliar?[indexPath.row] 


      guard (auxiliar?.count)! > indexPath.row else { 
       print("Index out of range") 
       return 
      } 

      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! MealsDetailsController 
      viewController.passedValue = (meal1?.familiy_id)! 
      viewController.name = (meal1?.shopname)! 

      print("\(meal1?.familiy_id) im the search ") 
      view.animateRandom() 
      self.present(viewController, animated: true , completion: nil) 




     } else { 
      let meal = shops[indexPath.row] 


      guard shops.count > indexPath.row else { 
       print("Index out of range") 
       return 
      } 

      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! MealsDetailsController 
      viewController.passedValue = meal.familiy_id 
      viewController.name = meal.shopname 
      view.animateRandom() 
      self.present(viewController, animated: true , completion: nil) 


     } 

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { 
     auxiliar = shops.filter { $0.shopname.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil} 
     if searchText == "" || searchBar.text == nil { 
      auxiliar = shops 
     } 
     tableView.reloadData() 
    } 

충돌이 let meal1 = auxiliar?[indexPath.row]

+1

어떤 코드가 오류를 발생시키고 있습니까? [Minimal, Complete and Verifiable example] (https://stackoverflow.com/help/mcve)을 제공해주십시오. 서로 관련이 없지만'else' 브랜치가없는 별도의'if' 절 대신에'switch' 문을 사용하여 코드를 읽기 쉽게 만들어야합니다. –

+0

'let meal1 = auxiliar? [indexPath.row]' – leo0019

답변

1

당신은 다음과 같은 두 문장 교환해야이 선으로 원인 :

let meal1 = auxiliar?[indexPath.row] 
guard (auxiliar?.count)! > indexPath.row else { 
    print("Index out of range") 
    return 
} 

그것은을 발생시키는 첨자을 (시도하는 말도 안돼을 예외가있는 경우는 auxiliar.count <= indexPath.row) 서브 스크립팅이 실제로 안전한지 검사하십시오.

그것은해야한다 :

guard auxiliar.count > indexPath.row else { 
    print("Index out of range") 
    return 
} 
let meal1 = auxiliar[indexPath.row] 

는 또한, var auxiliar: [Shops]? = [Shops]()는 이해되지 않는다. 기본값을 auxiliar으로 지정하면이 값을 Optional으로 정의하는 이유는 무엇입니까? 그냥 auxiliar을 비 선택 사항으로 선언하면 var auxiliar = [Shops]()이됩니다. 당신이이 경우에 함수가 결코 도달 할 수 있기 때문에 당신이 selectedIndex를 재설정하지 않으면 쉽게 문제를 일으킬 수있는 반환 할 값을 결정하기 위해 두 개의 서로 다른 변수를 확인하기 때문에

또한, 당신은 tableView(:numberOfRowsInSection:)의 구현을 방문한다 if searchActive 부분.

또한 코드를 리팩터링하고 if 문이 아닌 else 개의 분기 문이 아닌 switch 문을 사용해야합니다.

+0

답장을 보내 주셔서 감사합니다! 나는 그것을 고쳤다. 그리고 지금 부서지는 것은 아니다. 그러나 검색의 결과는 정확하지 않다. – leo0019

+0

나는 내 질문에'textDidChange'를 추가했다. 어떻게 코딩했는지를 보라. – leo0019