Dictionary는 '키' 값이 유효하지 않을 경우에 nil을 반환하지만,
Array의 경우에는 Out of Bounds와 함께 app crash가 발생한다.
array를 안전하게 사용하기 위해서 아래 코드처럼 사용할 수 있다.
extension Array {
subscript(safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
~= 연산자
패턴을 비교하는 연산자이다
static func ~= (pattern: Range<Array<Element>.Index>, value: Int) -> Bool
~= 을 사용하지 않았다면 아래 코드와 같이 표현해야되지만, ~=을 사용하면 깔끔하게 표현할 수 있다.
if index >= 0 && index < endIndex { }
'Swift > Foundation' 카테고리의 다른 글
Properties (0) | 2020.08.06 |
---|---|
Dispatch Queue (0) | 2020.08.04 |
class, struct (0) | 2020.08.03 |
Bridging (0) | 2020.07.06 |
MVC Design Pattern (0) | 2020.06.28 |