Swift:如何检查变量是否存在

时间:2017-09-08 18:53:26

标签: arrays swift null-check

我试图检查Swift中是否存在变量(或者更确切地说是数组的特定索引)。

如果我使用

if let mydata = array[1] {

如果索引有值,我会收到错误,如果索引没有,我会收到错误。

如果我使用

if array[1] != nil {

我收到编译器警告和/或崩溃。

基本上,我只是尝试获取命令行参数(这是任何文件名)并检查它们是否已被包含。我见过的命令行参数的所有示例都使用switch / case语句,但要检查已知文本,而不是改变文件名。

我仍在使用以下内容使Xcode中的索引超出范围错误:

if arguments.count > 1 {
    var input = arguments[2]
} else {
}

4 个答案:

答案 0 :(得分:5)

试试这个:

extension Collection where Indices.Iterator.Element == Index {

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

然后:

if let value = array[safe: 1] {
    print(value)
}

现在你甚至可以这样做:

textField.text = stringArray[safe: anyIndex]

不会导致崩溃,因为textField.text可以为nil,[safe:]下标总是返回值,如果存在则为nil,如果不存在则为nil

答案 1 :(得分:2)

if index < myData.count {
  // safe to access 
  let x = myData[index]
}

答案 2 :(得分:1)

您可以使用contains方法检查数组中是否存在值。

例如:

let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { $0 > 100 } // hasBigPurchase is a boolean saying whether the array contains the value or not.

检查其documentation以获取更多信息。

答案 3 :(得分:1)

<强>简单地下, 检查索引:

if index < array.count {
// index is exist

let data = array[index]

}