如何算一个元素出现在雨燕阵列? [英] How to count occurrences of an element in a Swift array?

查看:123
本文介绍了如何算一个元素出现在雨燕阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过的这几个例子,但所有这些似乎依靠知道你要计算的出现哪个元素。所以我不知道我要算的(我想指望所有的人的出现)的出现哪个元素的方式我的数组是动态生成的。谁能指教?

I've seen a few examples of this but all of those seem to rely on knowing which element you want to count the occurrences of. My array is generated dynamically so I have no way of knowing which element I want to count the occurrences of (I want to count the occurrences of all of them). Can anyone advise?

在此先感谢

编辑:

也许我本来应该更清晰,阵列将包含多个不同的字符串(例如
[富,富,BAR,FOOBAR]

Perhaps I should have been clearer, the array will contain multiple different strings (e.g. ["FOO", "FOO", "BAR", "FOOBAR"]

我怎样才能算富,酒吧和Foobar的出现不知道他们是事先什么?

How can I count the occurrences of foo, bar and foobar without knowing what they are in advance?

推荐答案

您可以使用类型的字典 [字符串:INT] 来建立计数每个在项目的 [字符串]

You can use a dictionary of type [String:Int] to build up counts for each of the items in your [String]:

let arr = ["FOO", "FOO", "BAR", "FOOBAR"]
var counts:[String:Int] = [:]

for item in arr {
    counts[item] = (counts[item] ?? 0) + 1
}

print(counts)  // "[BAR: 1, FOOBAR: 1, FOO: 2]"

for (key, value) in counts {
    print("\(key) occurs \(value) time(s)")
}

输出:

BAR occurs 1 time(s)
FOOBAR occurs 1 time(s)
FOO occurs 2 time(s)

这篇关于如何算一个元素出现在雨燕阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆