在Swift标准库的协议中使用typealias语法

在Swift标准库的协议中使用typealias语法,swift,generics,standard-library,Swift,Generics,Standard Library,在Apple的Swift编程指南中,描述了如何在协议中使用typealias关键字(来自泛型部分) 然后实施: struct IntStack: Container { typealias ItemType = Int // can sometimes be left out and inferred by the compiler mutating func append(item: Int) { self.push(item) } // redacted } 然而,在

在Apple的Swift编程指南中,描述了如何在协议中使用typealias关键字(来自泛型部分)

然后实施:

struct IntStack: Container {
  typealias ItemType = Int // can sometimes be left out and inferred by the compiler
  mutating func append(item: Int) {
    self.push(item)
  }

// redacted
}
然而,在Swift标准库中发现了一个明显不同的用例,例如

public protocol ForwardIndexType : _Incrementable {

typealias Distance : _SignedIntegerType = Int

// redacted

}

公共协议集合类型:可索引,SequenceType{
typealias生成器:GeneratorType=索引生成器
public func generate()->Self.Generator
//编辑
}
连同:

extension CollectionType where Generator == IndexingGenerator<Self> {
  public func generate() -> IndexingGenerator<Self>
}
extensioncollectiontype,其中Generator==IndexingGenerator{
public func generate()->索引生成器
}
这个语法代表什么?typealias似乎同时被声明、限制(例如,限制为GeneratorType)和赋值?这意味着什么?为什么?我只希望在实现客户机代码时看到赋值(=)

我对typealias的理解是,它表示一个类型,由实现代码(按照泛型)“填充”,但在这里,它似乎在声明中为typealias实现了一个类型,即使这也在扩展中完成(我希望它在扩展中完成)。

看一看。冒号表示继承,等号表示赋值

据我理解,这意味着:

typealias X // defines associated type X for subclasses to override
typealias X: Y // defines associated type X and requires that it conform to Y
typealias X = Z // defines associated type X with a default of type Z
typealias X: Y = Z // defines associated type X with a default of type Z and requires that any overrides conform to Y
我的解释似乎得到了Swift泛型的支持:

关联类型由协议使用typealias声明 关键词。它通常由符合该协议的项目设置, 尽管您可以提供默认值。与类型参数类似,一个 在生成泛型类型时,关联类型可以用作标记 规则


在定义关联类型时,使用关键字
typealias
可能会产生误导,并可能被中的
associatedtype
替换

协议定义中的
typealias X=Z
不分配别名。它用默认值
Z
@MartinR-True定义了一个关联类型
X
,我的措辞很糟糕。我会改正的。谢谢鉴于泛型的设计目的是为了更好地使用,泛型。。。我仍然不是100%理解为什么存在关联类型具有默认值的能力,但仍然是@Brynjar,因为默认值在大多数情况下都是正确的。例如,如果使用默认的
生成器
,则会得到一个
索引生成器
。此生成器适用于支持的任何类,该类通过使用标准实现来节省工作并防止bug。它仍然是通用的,只是针对遵循特定协议的类进行了优化。
extension CollectionType where Generator == IndexingGenerator<Self> {
  public func generate() -> IndexingGenerator<Self>
}
typealias X // defines associated type X for subclasses to override
typealias X: Y // defines associated type X and requires that it conform to Y
typealias X = Z // defines associated type X with a default of type Z
typealias X: Y = Z // defines associated type X with a default of type Z and requires that any overrides conform to Y