计数变量值为0的次数

时间:2017-04-28 11:06:12

标签: arrays swift

我有来自服务器的json输出

posts =     (
            {
         address = "";
        "key_number" = A80;
        name = "";
        Id = 103;
        visited = 1;
    },
            {
       address = "";
       key_number = K3;
       name = "";
       Id = 110;
       visited = 0;
    },
     {
       address = "";
       key_number = B67;
       name = "";
       Id = 109;
       visited = 0;
    }
);

我想得到所访问的总数= 0。 如何在快速代码中实现?

1 个答案:

答案 0 :(得分:6)

您可以对阵列使用filter并查找计数。

let posts = yourJson["posts"] as? [[String:Any]] ?? []
let filterPostsCount = posts.filter { $0["visited"] as? Int == 0 }.count
print(filterPostsCount)