본문 바로가기
Swift

[Swift] Safe Index

by be_beee 2023. 1. 7.
extension Array {
    subscript (safe index: Int) -> Element? {
    	// iOS 9 or later
        return indices ~= index ? self[index] : nil	
        // iOS 8 or earlier
        // return startIndex <= index && index < endIndex ? self[index] : nil
        // return 0 <= index && index < self.count ? self[index] : nil
    }
}

let list = [1, 2, 3]
list[safe: 4] // nil
list[safe: 2] // 3

 

출처: http://minsone.github.io/programming/check-index-of-array-in-swift

'Swift' 카테고리의 다른 글

[Swift] sync, async, serial, concurrent  (0) 2023.01.17
[Swift] method swizzling  (0) 2023.01.11
[Swift] dynamic var, @objc, @NSManaged  (0) 2023.01.07
[Swift] final (feat. Method Dispatch)  (0) 2023.01.05
#0. 목적  (0) 2020.04.14