Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array 요소에 안전하게 접근하기 #52

Closed
kimkyuchul opened this issue Jan 25, 2024 · 0 comments
Closed

Array 요소에 안전하게 접근하기 #52

kimkyuchul opened this issue Jan 25, 2024 · 0 comments
Assignees

Comments

@kimkyuchul
Copy link
Owner

extension Collection {
    subscript(safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}
  • array 요소에 접근할 때 해당 요소가 없을 시 Index out of range error를 방출해 앱이 강제종료 된다.
  • subscript를 통해 범위를 벗어나면 nil을 반환하도록 할 수 있다.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let data = tableViewModel?.voteArtistList?[safe: indexPath.row] {
	// array의 IndexPath에 요소 존재 시 로직
        } else {
	 // 데이터 없을 시 로직 
        }
     }
  }
  • 다음과 같이 cellForRowAt에서 활용해서 array 요소에 안전하게 접근하면서 데이터 유무에 따른 로직도 처리할 수 있었다.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant