ios - 如何在 Swift 中分配一个可以为 null 的数组元素?

标签 ios swift option-type

在我的 Swift 应用程序中,我正在查询一个返回 json 对象的 api,如下所示:

{
    key1: value1,
    key2: value2,
    array : [
        {
            id: 1,
            string: "foobar"
        },
        {
            id: 2,
            string: "foobar"
        }
    ]
}

事实:

  • 数组值可以为空。
  • 我想读取第一个数组元素, 存在与否。

在 Swift 中我正在做:

  if let myArray: NSArray = data["array"] as? NSArray {
      if let element: NSDictionary = myArray[0] as? NSDictionary {
          if let string: NSString = element["string"] as? NSString {
              // i should finally be able to do smth here,
              // after all this crazy ifs wrapping
          }
      }
  }

如果数组和第一个元素存在,它会工作,但即使元素赋值在 if let 包装内,我也会因“索引 0 超出空数组边界”而崩溃。

我在这里做错了什么?我对 Swift 的可选项、打字和疯狂的 if let wrapping 无处不在感到疯狂......

最佳答案

错误与Optional无关。如果您对数组使用 subscription([]),则必须检查它的长度。

if let myArray: NSArray = data["array"] as? NSArray {
    if myArray.count > 0 { // <- HERE
        if let element: NSDictionary = myArray[0] as? NSDictionary {
            if let string: NSString = element["string"] as? NSString {
                println(string)
            }
        }
    }
}

但我们手头有.firstObject属性

The first object in the array. (read-only)

If the array is empty, returns nil.

使用这个:

if let myArray: NSArray = data["array"] as? NSArray {
    if let element: NSDictionary = myArray.firstObject as? NSDictionary {
        if let string: NSString = element["string"] as? NSString {
            println(string)
        }
    }
}

而且,我们可以使用 "Optional Chaining"语法:

if let str = (data["array"]?.firstObject)?["string"] as? NSString {
    println(str)
}

关于ios - 如何在 Swift 中分配一个可以为 null 的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28277239/

相关文章:

ios - 以编程方式将文本插入 UITextView 而不移动插入符号位置。

swift - 在 SwiftUI 中的 ForEach 中使用 id 时,如何对数组的索引进行动画处理

ios - 安装 pod 失败,尽管它在设置新机器之前有效

ios - 如果让 - 多个条件

c++ - 如何测试 C++ 的功能支持?

ios - 我可以使用某种方法来获取变量名吗?

ios - AVAudioSession 类别变为 nil 并且 mediaServicesWereReset,avplayer 播放一直失败

ios - VIPER 的可重用 View /模块

ios - RatingControl - 从 viewController 中捕获点击的星星数

java - 空 `Optional` 类型的返回值应该是什么?