簡體   English   中英

檢查對象是否超出數組范圍的最佳方法

[英]Best way to check if object is out of bounds in array

在Array中的特定索引處檢查對象是否存在(在邊界內)的最佳實踐是什么?

讓它像這樣簡單會很好,但不幸的是,這是不可能的:

let testArray = ["A", "B", "C", "D"]

if let result = testArray[6] {
    println("Result: \(result)")
}
else {
    println("Result does not exist. Out of bounds.")
}

我是否需要檢查總數?

謝謝!

您還可以對Array進行擴展,這樣您就可以使用if-let進行檢查:

extension Array {
    func at(index: Int) -> Element? {
        if index < 0 || index > self.count - 1 {
            return nil
        }
        return self[index]
    }
}

let arr = [1, 2, 3]

if let value = arr.at(index: 2) {
    print(value)
}

您可以將~=運算符與indices函數結合使用,這是創建容器的完整索引范圍范圍的快捷方式:

let a = [1,2,3]
let idx = 3  // one past the end

if indices(a) ~= idx {
    println("within")
}
else {
    println("without")
}

需要注意的一點是,它適用於具有可比索引的任何類型的容器,而不僅僅是具有整數索引的數組。 將索引視為數字通常是一個很好的習慣,因為它可以幫助您更一般地思考沒有這些索引的容器上的算法,例如字符串或詞典:

let s = "abc"
let idx = s.endIndex

idx < count(s)  // this won't compile

idx < s.startIndex  // but this will

// and so will this
if indices(s) ~= idx {
    println("within")
}
else {
    println("without")
}

算法越普遍,您就越有可能將它們分解為泛型並增加重復使用。

@alkku有它,但為了簡單和使用所有語言中最未充分利用的語法形式?: ::

extension Array {
    func atIndex(index: Int) -> T? {
      return (0 <= index && index < self.count
              ? self[index]
              : nil)
    }
}

檢查所使用的對象索引是否應該大於或等於零,並且應該減少數組的總數,如下所示:

//Here index is object you want for
if(index >= 0 && index < [yourArray count])
{
   //inside of array
}
else
{
   //out of bound
}

在Swift中有一種新的(簡潔的)方法:

array.indices.contains(index)

要檢查索引是否在swift中的數組范圍內,您可以使用

if index < testArray.count {
    //index is inside bounds
} else {
    //index is outside bounds
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM