iOS
[Swift] 안전하게 배열 조회 (feat: indices)
Peppo
2022. 9. 5. 00:28
728x90
오늘은 안전하게 배열을 조회하는 방법에 대해 알아 보려고 합니다.
아래와 같이 배열을 조회하다 엉뚱한 index에 접근하게 되면,
이런 에러를 많이 보실겁니다.
let arr = [1, 2, 3]
for index in 0...10 {
print(arr[index]) // Fatal error: Index out of range
}
Fatal error: Index out of range
Array(배열)의 경우에는 index를 접근해서 가져오는 값이 Optional이 아니라
guard를 쓸 수도 없어 index가 유효하지 않을 경우 꼼짝없이 앱이 다운되어 버립니다.
이런 오류를 방지하기 위해
extension을 이용해 아래와 같은 코드를 적용해줍니다.
extension Array {
subscript (safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
분석해볼게요
Collection 타입은 indices를 갖는데,
indices란, 해당 배열의 범위 라고 생각하시면 됩니다.
아래 코드를 보면 이해가 가실 겁니다.
let arr = [1, 4, 3]
print(arr.indices) // 0..<3
다시 extension에서 썼던 코드로 돌아가 볼게요.
return 쪽 코드를 보면,
return indices ~= index ? self[index] : nil
범위 내 index가 있으면, 해당 index를 반환하고,
아니면 nil을 반환하게 해서
fatal error: Index out of range 의 에러는 더이상 뜨지 않게 됩니다.
응용
extension Array {
subscript (safe index: Index) -> Element? {
return indices ~= index ? self[index] : nil
}
}
let arr = [1, 2, 3]
for index in 0...10 {
if let item = arr[safe: index] {
print(item)
} else {
print("else: \(arr[safe: index])")
}
}
// 1
// 2
// 3
// else: nil
// else: nil
// else: nil
// else: nil
// else: nil
// else: nil
// else: nil
// else: nil
728x90