Swift 没有类型的类型别名

Swift typealias without type

右边表达式中没有类型的类型别名有什么作用?

在示例中,当另一个类型别名已存在于 BooleanLiteralConvertible 之外时,在 BooleanLiteralConvertible 中创建 BooleanLiteralType 的目的是什么?他们有关系吗?

    /// Conforming types can be initialized with the Boolean literals
    /// `true` and `false`.
    protocol BooleanLiteralConvertible {
        typealias BooleanLiteralType

        /// Create an instance initialized to `value`.
        init(booleanLiteral value: Self.BooleanLiteralType)
    }


    /// The default type for an otherwise-unconstrained Boolean literal.
    typealias BooleanLiteralType = Bool

Swift 语言参考中的定义

Protocol Associated Type Declaration

Protocols declare associated types using the keyword typealias. An associated type provides an alias for a type that is used as part of a protocol’s declaration. Associated types are similar to type parameters in generic parameter clauses, but they’re associated with Self in the protocol in which they’re declared. In that context, Self refers to the eventual type that conforms to the protocol. For more information and examples, see Associated Types.

它为协议声明了一个类型成员,您可以在协议方法定义中引用它。这允许定义通用协议。

例如

protocol Foo {
  typealias FooType

  func echo(x: FooType)
}

class Baz<T: Comparable>: Foo {
  typealias FooType = T

  func echo(x: FooType) {
    println(x)
  }
}

Baz().echo(2) // "2"
Baz().echo("hi") "hi"

函数 echo 是完全通用的,因为 FooType 是任何类型。 class 实施 Foo 协议然后可以相应地改进和指定 FooType

在示例中,我们使用了另一种通用类型 (T),因此 FooType 不会被细化为仅 Comparable 类型。


关于默认类型别名,这编译

protocol Foo {
  typealias FooType

  func echo(x: FooType)
}

typealias FooType = Bool

class Bar: Foo {
  func echo(x: FooType) { // no local definition for `FooType`, default to `Bool`
    println(x)
  }
}

虽然这不是

protocol Foo {
  typealias FooType

  func echo(x: FooType)
}

class Bar: Foo {
  func echo(x: FooType) { // `FooType` can't be resolved as a valid type
    println(x)
  }
}