我见过几个这样的示例,但所有这些示例似乎都依赖于知道要计算哪个元素的出现次数.我的数组是动态生成的,所以我无法知道要计算哪个元素的出现次数(我想统计所有元素的出现次数).有人能给点建议吗?

提前谢谢你

编辑:

也许我应该更清楚,数组将包含多个不同的字符串(例如.

如果事先不知道foo、bar和foobar是什么,我怎么计算它们的出现次数呢?

推荐答案

Swift 3 and Swift 2:

您可以使用类型为[String: Int]的字典为[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)

Swift 4:

SWIFT 4 introduces (SE-0165)能够在字典查找中包含默认值,结果值可以通过+=-=等操作进行变异,因此:

counts[item] = (counts[item] ?? 0) + 1

变成:

counts[item, default: 0] += 1

这使得使用forEach在一行简明的代码中执行计数操作变得很容易:

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

arr.forEach { counts[$0, default: 0] += 1 }

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

Swift 4: 100

SWIFT 4引入了新版本的reduce,它使用inout变量来累加结果.使用这一点,计数的创建就真正变成了一行:

let arr = ["FOO", "FOO", "BAR", "FOOBAR"]
let counts = arr.reduce(into: [:]) { counts, word in counts[word, default: 0] += 1 }

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

或使用默认参数:

let counts = arr.reduce(into: [:]) { $0[$1, default: 0] += 1 }

最后,您可以将其作为Sequence的扩展,以便可以在包含Hashable项(包括ArrayArraySliceStringString.SubSequence)的任何Sequence上调用它:

extension Sequence where Element: Hashable {
    var histogram: [Element: Int] {
        return self.reduce(into: [:]) { counts, elem in counts[elem, default: 0] += 1 }
    }
}

这个 idea 是从this question借来的,不过我改成了computed property.感谢@LeoDabus建议扩展Sequence而不是Array来获取额外的类型.

Examples:

print("abacab".histogram)
["a": 3, "b": 2, "c": 1]
print("Hello World!".suffix(6).histogram)
["l": 1, "!": 1, "d": 1, "o": 1, "W": 1, "r": 1]
print([1,2,3,2,1].histogram)
[2: 2, 3: 1, 1: 2]
print([1,2,3,2,1,2,1,3,4,5].prefix(8).histogram)
[1: 3, 2: 3, 3: 2]
print(stride(from: 1, through: 10, by: 2).histogram)
[1: 1, 3: 1, 5: 1, 7: 1, 9: 1]

Ios相关问答推荐

如何从ipad获取用户定义的设备名称,IOS版本应大于16在flutter

当包含UITextView的inputAccessoryView显示键盘时,iOS UITableView内容会出现UINavigationBar奇怪的错误

如何让3张组合的`SF Symbol`图片围绕一个特定点旋转?

如何在Android或iPhone上的原生react 中处理其他应用程序通知?

更新 flutter 和 xcode 后 Xcode 14.3 中缺少文件 (libarclite_iphoneos.a)

将 URLCache 子类与 URLSession 一起使用

占位符文本未显示在 TextEditor 上

我正在try 制作一种 Select 器样式,例如设置中的外观 Select 器

在 Swift 中映射 MySQL 数据

SwiftUI 图像与下拉视图切换一起 skip

SwiftUI 选项卡式视图防止滑动到下一个选项卡

.onChange(of: ) 一次用于多个 @State 属性?

clipShape swift的三元

SensorKit - 获取数据不调用结果委托函数

如何使用 Swift 文档注释

Xcode - 错误 ITMS-90635 - Bundle 包中的 Mach-O 无效 - 提交到 App Store

从 NSUserDefaults 字典 iOS 中删除所有键

UITextView 内容插图

iTunes Connect 中的无限制 Web 访问是什么意思

由于 GoogleSignIn、AdMob 提交应用程序时 iOS 10 GM 发布错误应用程序try 在没有使用说明的情况下访问隐私敏感数据