Swift
[Swift] 안전하게 배열 접근하기
wody
2022. 4. 26. 19:00
참고한 StackOverflow
Safe (bounds-checked) array lookup in Swift, through optional bindings?
If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error: var str = ["Apple", "Banana", "Coconut"] str[0] // "Apple" str[3] //
stackoverflow.com
배열의 특정 인덱스에 접근하는 일이 드물지만, 배열을 안전하게 접근하는 방법에 대해 공유합니다.
확장
// 출처 : https://stackoverflow.com/questions/25329186/safe-bounds-checked-array-lookup-in-swift-through-optional-bindings/30593673#30593673%EF%BB%BF
extension Collection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
사용
var testCase = [0, 1, 2, 3, 4]
print(testCase[safe: 3]) // Optional(3)
print(testCase[safe: 6]) // nil
이렇게 하면 좋은 점
1. Fatal error: Index out of range 에러가 나지 않는다!
2. (인덱스로 접근할 때 마다)배열 카운트와 접근 인덱스를 비교 할 필요가 없다