在The Swift Programming Language
书,可在 iBooks Store
上找到, 在 Generics
这一章,在接近尾声的某个地方,它在讨论了 constraints
之后讨论了 Generic Where Clauses和 type constraints
.
给出以下协议(protocol):
protocol Container {
associated type Item: Equatable
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
}
然后声明以下函数:
func allItemsMatch<C1: Container, C2: Container>(_ someContainer: C1, _ anotherContainer: C2) -> Bool where C1.Item == C2.Item, C1.Item: Equatable {
// Check that both containers contain the same number of items.
if someContainer.count != anotherContainer.count {
return false
}
// Check each pair of items to see if they're equivalent.
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// All items match, so return true.
return true
}
为了演示这一点,之前声明了以下结构:
struct Stack<Element>: Container {
// original Stack<Element> implementation
var items = [Element]()
mutating func push(_ item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(_ item: Element) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Element {
return items[i]
}
}
现在我们来谈谈我在 Xcode(v9.0,macOS 10.12.6 FYI)中遇到的问题:
var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")
var arrayOfStrings = ["uno", "dos", "tres"]
if allItemsMatch(stackOfStrings, arrayOfStrings) {
print("All items match.")
} else {
print("Not all items match.")
}
我在最后一个 if-else
的第一行旁边收到以下错误声明:
Cannot invoke 'allItemsMatch' with an argument list of type '(Stack2<String>, [String])'
因为我学习编程才三个月(而且是从头开始),所以我不知道为什么这会失败,因为我正在严格按照书上的要求去做。 有人可以解释为什么会抛出错误并提出可能的解决方案吗?
最佳答案
这里有两个问题:
- 您错误地复制了协议(protocol)定义,它应该是:
protocol Container {
associatedtype Item
mutating func append(_ item: Item)
var count: Int { get }
subscript(i: Int) -> Item { get }
}
- 您忘记将符合
Array
的重要行添加到Container
:
extension Array: Container {}
关于swift - Swift 编程语言 - 泛型 - Where 子句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47210062/