0

我正在阅读 Apple 出版的 Swift 书籍。我有 XCode 7.2.1 下面的代码给出了编译错误。我在操场上使用了代码。

protocol Container {
    associatedtype ItemType
    mutating func append(item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

您可以在页面的后半部分看到代码。

这是错误: 在此处输入图像描述

我不确定这是否是对代码的正确更改;但是当我将协议中的第一行从

associatedtype ItemType

typealias ItemType

错误消失了。

4

2 回答 2

1

Xcode 7.2.1 仍在 Swift 2.1 上。

在 Xcode 7.3(当前版本的 Xcode)中,Xcode 开始使用 Swift 2.2 版。

在 Swift 2.1 和 2.2 版本之间,使用typealiaswithin 协议被更改为 newassociatedType关键字。

话虽如此,您在 Apple 出版的 Swift 书中查看的文档已更新为 Swift 2.2 语法,但是您使用的 Xcode 版本尚未更新为 Swift 2.2 语法。

因此,正如您正确了解的那样,通过在您的协议中使用typealias代替associatedType,它将在 Xcode 7.2.1 中正确编译。

但可能应该建议,如果可能,您继续升级到 Xcode 7.3 并使用 Swift 2.2。如果您这样做,Apple 的 Swift 书中更新的 Swift 2.2 示例将在您的 Xcode 中完美运行。

于 2016-05-01T17:09:28.403 回答
-1

是的,该关键字在 Swift 2.2 版中确实发生了变化。https://github.com/apple/swift-evolution/blob/master/proposals/0011-replace-typealias-associated.md

于 2016-05-01T14:40:59.080 回答