[Swift] 如何「安全」取出陣列中的值?

無論在何種語言,都可能遇到取陣列的 index 超出陣列的大小而造成 Crash 的現象,在 Swift 中當然也不例外,那我們如何預防這件事的發生呢?傳統方法是先去檢查陣列的長度,再判斷 index 是不是越界,但在 Swift 中這太笨重了,我們只要利用一個小小 Collection 的擴充就可以囉!

swift

首先,先看來一下這個擴充怎麼寫吧!

extension Collection {
 
    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

再來,假設我們有一段程式如下,要取值只要使用「陣列名稱[safe: index]」就可以囉

let index0 = array[safe: 0] // Prints 100
let index1 = array[safe: 1] // Prints 200
let index6 = array[safe: 6] // Prints nil


比較一下傳統的方法,要先判定陣列的長度,再去取值,這樣整個就慢囉

let array = [100, 200, 300 , 400 , 500, 100]  // Prints [100, 200, 300, 400, 500, 100]
let count = array.count
let index6 = 6
if index6 < count {
    let object6 = array[index6]
}
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments