我调用测试方法Expression type '()' is ambiguous without more context
时看到错误XCTAssertEqual
。我尝试将[(Character,Int)]
显式添加到expected
,但仍然看到此错误。我不确定还有什么尝试。
如何使Swift编译器了解?
测试:
func testFrequencyCountOnInput() {
let huff = Huffman("ANNA")
let expected: [(Character,Int)] = [("A", 2), ("N", 2)]
XCTAssertEqual(huff.frequency, expected)
}
代码:
class Huffman {
private(set) var frequency: [(Character, Int)]
init(_ input: String) {
self.frequency = Huffman.sortedFrequency(for: input)
}
static private func sortedFrequency(for input: String) -> [(Character, Int)] {
var frequency = [Character: Int]()
for char in input {
frequency[char] = (frequency[char] ?? 0) + 1
}
let sorted = Array(frequency).sorted(by: {$0.1 > $1.1})
return sorted
}
}
答案 0 :(得分:0)
我认为在这里使用Tuple
并不是一个好主意。相反,您可以将其重构为某种类型。例如:
struct Frequency: Equatable {
let char: Character
let count: Int
}
Struct
很好,它是一个值类型(作为Tuple
)和can automatically synthesize conformance to Equatable
protocol。
下一步是Huffman
类。对于这么小的问题,您有大量的代码。我们也尝试重构它:
final class Huffman {
private(set) var frequency: [Frequency]
init(_ input: String) {
frequency = input.counts
.map { Frequency(char: $0.key, count: $0.value) }
.sorted(by: { $0.count > $1.count })
}
}
extension String {
var counts: [Character: Int] {
return reduce(into: [:]) { d, c in
d[c] = d[c, default: 0] + 1
}
}
}
请注意,此代码计算String
扩展名的counts
属性(可能不是最好的名字)中的频率,然后将map
的结果计算为[Frequency]
,最后对它进行排序一个大问题。更少的代码,更准确。
在这里,我们进行单个测试:
func testFrequencyCountOnInput() {
let huff = Huffman("ANNNA")
let expected: [Frequency] = [
Frequency(char: "N", count: 3),
Frequency(char: "A", count: 2)
]
XCTAssertEqual(huff.frequency, expected)
}
即使sort
功能也可以正常工作。