2017-12-10 7 views
0

오버라이드 된 메서드, delegate 메서드 또는 dataSource 메서드와 같은 비 던진 함수에서 오류를 처리하는 데 문제가 있습니다. 나는 오류를 로깅 할 때만 생각났다. 그리고 이것이 좋은 오류 처리 전략이 아니라는 것을 알았다. 다른 방법이나 접근법 등이 있습니까? 고맙습니다.Swift의 비 던지기 함수에서의 오류 처리

편집 :

enum SomethingError : Error{ 
    case somethingFailed 
} 

var anObject : AnObject? 

........ 
........ 


public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{ 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) 

     guard let anObject = anObject else{ 
      throw SomethingError.somethingFailed 
      //and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return" 
     } 

     ..... 
     ..... 

     return cell 
} 

당신이 있기 때문에, 같은 것을 할 수 없습니다 cellForItemAt : indexPath가 던지는 기능이 아니고, 셀을 반환해야 collectionView. 어떻게하면 오류를 잡을 수 있습니까? 이것이 문제입니다. 로깅을 통해서만?

편집 : 나는 if let이지만 을 사용할 수 있음을 알고 있습니다. 여기에 오류를 처리하십시오.

+0

구체적인 예가 도움이 될 것입니다. –

+0

오류가 발생하지 않으므로 "오류"를 정의 하시겠습니까? 방법의 예가 있습니까? – Larme

+1

** 당신은 ** cellForItem'에서 **'throw '할 수는 없지만 던져진 에러는'catch' 할 수 있습니다. 기본적으로 범위를 종료 할 수있는 델리게이트 및 데이터 소스 메서드의 코드는 사용하지 마십시오. – vadian

답변

1

명시 적으로 필요하지 않은 프로토콜의 구현에서 오류를 전파 할 수 없습니다.

동일한 구현에서 throw/catch을 사용할 수도 있고 단순히 오류를 처리하는 메서드를 호출 할 수도 있습니다.

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{ 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) 

     do { 

      guard let anObject = anObject else{ 
       throw SomethingError.somethingFailed 
       //and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return" 
     } catch SomethingError.somethingFailed { 
      // handle the error here 
     } 

     ..... 
     ..... 

     return cell 
} 

을 단지 기능으로는 다음과 같이 될 것입니다 : 당신의 예에서이 같은 throw/catch 사용할 수 있습니다

func handleError() { 
    // handle error 
} 

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{ 
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) 

     guard let anObject = anObject else{ 
      handleError() 
      return 
     } 

     ..... 
     ..... 

     return cell 
} 

자세한 내용은 당신이 읽을 수있는 오류 처리 신속 약 : The Swift Programming Language: Error Handling