我正在关注Generic
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html的Apple
教程。
但是在教程结束时。我遇到了一些问题:
var myStack = Stack<String>()
myStack.push("a")
myStack.push("b")
myStack.push("c")
var arrayOfStrings = ["a", "b", "c"]
if allItemsMatch(myStack, arrayOfStrings) {
print("All items match.")
} else {
print("Not all items match.")
}
在第if allItemsMatch(myStack, arrayOfStrings)
行,它说:
无法调用allItemsMatch&#39;使用类型的参数列表 &#39;(Stack&lt; String&gt;,[String])&#39;
这是我的代码:
import UIKit
struct Stack<Element> {
var items = [Element]()
mutating func push(item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
}
extension Stack {
var topItem: Element? {
return items.isEmpty ? nil : items[items.count - 1]
}
mutating func append(item: Element) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Element {
return items[i]
}
}
func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
}
return nil
}
let doubleIndex = findIndex([3.14159, 0.1, 0.25], 9.3)
let stringIndex = findIndex(["Mike", "Malcolm", "Andrea"], "Andrea")
protocol Container {
associatedtype ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
extension Array: Container {}
func allItemsMatch< C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable> (someContainer: C1, _ anotherContainer: C2) -> Bool {
if someContainer.count != anotherContainer.count {
return false
}
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
return true
}
var myStack = Stack<String>()
myStack.push("a")
myStack.push("b")
myStack.push("c")
var arrayOfStrings = ["a", "b", "c"]
if allItemsMatch(myStack, arrayOfStrings) {
print("All items match.")
} else {
print("Not all items match.")
}
我错过了什么地方?
答案 0 :(得分:2)
您从未明确地将Stack<Element>
结构符合您的Container
协议。因此,Swift严格的类型安全性会阻止您将其传递给需要符合Container
协议的参数(即使它隐式符合)。
您可以通过扩展程序明确地将Stack
与Container
一致。例如:
extension Stack:Container {}