愛 crash 的 array

在對 array 取值時若 index 超過 array 所含的內容數,會導致取值失敗而 crash,要如何讓 array 像 dictionary 一樣安全的取值,若無值則回傳 nil 呢?

 

為 Collection 加上安全取值特性

Array 是屬於 Collection types,因此我們可以對 Collection 加上一個 subscript,判斷傳進來的 index 是否包含在 array 中,若有則回傳值,否則回傳 nil

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
    }
}

 

使用範例

let array = [0, 1, 2]

var safeArray = array[safe: 0]
print("safeArray: \\(String(describing: safeArray))")
// output => safeArray: Optional(0)

safeArray = array[safe: 4]
print("safeArray: \\(String(describing: safeArray))")
// output => safeArray: nil