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

Swift: How to check a variable exists

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

如果我用

if let mydata = array[1] {

如果索引有值,我会得到一个错误,如果没有,我会崩溃。

如果我用

if array[1] != nil {

我收到编译器警告and/or 崩溃。

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

我仍然在 Xcode 中遇到索引超出范围的错误,错误如下:

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

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

例如:

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

查看其 documentation 了解更多信息。

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

试试这个:

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:] 下标总是 returns value if exists or nil if exists

简单, 检查索引:

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

let data = array[index]

}