swift - Swift 编程语言 - 泛型 - Where 子句的问题

标签 swift generics swift3 where-clause

The Swift Programming Language书,可在 iBooks Store 上找到, 在 Generics这一章,在接近尾声的某个地方,它在讨论了 constraints 之后讨论了 Generic Where Clausestype 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])'

因为我学习编程才三个月(而且是从头开始),所以我不知道为什么这会失败,因为我正在严格按照书上的要求去做。 有人可以解释为什么会抛出错误并提出可能的解决方案吗?

最佳答案

这里有两个问题:

  1. 您错误地复制了协议(protocol)定义,它应该是:
protocol Container {
  associatedtype Item
  mutating func append(_ item: Item)
  var count: Int { get }
  subscript(i: Int) -> Item { get }
}

part 1

  1. 您忘记将符合Array 的重要行添加到Container:
extension Array: Container {}

part 2

关于swift - Swift 编程语言 - 泛型 - Where 子句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47210062/

相关文章:

swift - 是否有任何可能的显式使用空元组 () 的实例(值),即 typealias 'Void' 的实例?

arrays - 如何从一个可观察对象数组创建一个数组的可观察对象?

java - 泛型上的通配符错误

generics - 如何初始化常量泛型数组?

swift - 将所有项目放入一个 Collection View 行中

ios - UITabBar 图标文字颜色

ios - 3D Touch 快速操作启动黑屏。 UiNavigationController->UITableViewController-> UIViewController

c++ - 对象没有命名类型 - C++

swift - NSKeyedUnarchiver.unarchiveObject() 取消归档旧对象

ios - 段错误: 11 with no files specified