【问题标题】:How to I look through an array that exists in a dictionary in Swift?如何查看存在于 Swift 字典中的数组?
【发布时间】:2017-03-16 06:32:11
【问题描述】:

我正在尝试遍历字典中存在的数组。 我做错了什么,这应该如何工作?

    public func getItemCount() -> Int{

        var count = 0
        for item in order.object(forKey:"items") as? Array {
            count += 1
            //other instructions
        }
        return count
    }

【问题讨论】:

  • 如果你不知道Array是什么类型,最好使用[AnyObject]。你可以看看我的回答。
  • 它的as? Array for 循环不能有可选的。要么使用有崩溃风险的as! Array,要么仅在数组不为零时将其分解并循环。
  • @Jargen89,我的回答解决了你的问题吗?

标签: ios arrays swift for-loop dictionary


【解决方案1】:

尝试将其分解为两个步骤。

public func getItemCount() -> Int{

    if let thisArray:[AnyObject] = order.object(forKey:"items") as? [AnyObject] {
       for item in thisArray {

       }
    }
}

随时提出修改建议。如果它不起作用,请告诉我

【讨论】:

  • 这是迄今为止最好的答案。
  • 是的,非常感谢。在使用 Objective-C 之后,我才开始接触 Swift。
猜你喜欢
  • 2014-10-25
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-10
相关资源
最近更新 更多