【问题标题】:Total number of elements from dictionary字典中的元素总数
【发布时间】:2019-07-19 16:04:55
【问题描述】:

我有一个[String: Any] 类型的字典,但我无法获得内部字典的元素总数。

struct ICP {
        let staff = [
            "teachers": [
                    [
                        "name": "Teacher One"
                    ],
                    [
                        "name": "Teacher Two"
                    ],
                    [
                        "name": "Teacher Three"
                    ],
                    [
                        "name": "Teacher Four"
                    ]
                ]
        ]  as [String : Any]
    }

我需要从上面的字典中得到教师的总数。

【问题讨论】:

  • staff["teachers"]?.count

标签: swift swift4


【解决方案1】:

首先,在ICP 结构中,您声明了一个名为staff 的常量变量,其中包含一个类型为[String: [[String: String]]] 或不久的[String: [Any]] 的字典,当您访问teachers 时,您将拥有一个单个字典的集合,其中有点像[[String: String]]

我建议你在ICP 类中创建一个方法并命名为teachersCount

斯威夫特 5.1

喜欢:

struct ICP {

    func teachersCount() -> Int {

        guard let teachers = staff["teachers"] as? [[String: String]] else {return 0}

        return teachers.count

   }

您可以在结构之外调用它,例如:

ICP().teachersCount()

在你的结构里面像:

self.teachersCount()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-04-29
    • 1970-01-01
    • 2016-02-27
    • 2021-08-11
    • 2012-09-29
    相关资源
    最近更新 更多