Boon
Boon

Reputation: 41510

Swift typealias without type

What does typealias without the type on the right expression do?

In the example, what's the purpose of creating a BooleanLiteralType within BooleanLiteralConvertible when another typealias already exists outside of it? Are they related?

    /// 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

Upvotes: 2

Views: 1376

Answers (2)

Gabriele Petronella
Gabriele Petronella

Reputation: 108169

It declares a type member for the protocol, which you can refer to in the protocol methods definition. This allows the definition of a generic protocol.

For instance

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"

The function echo is completely generic, as FooType is any type. The class implementing the Foo protocol can then refine and specify FooType accordingly.

In the example we're using another generic type (T) so that FooType is not refined to only Comparable types.


Concerning the default typealias, this compiles

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)
  }
}

while this doesn't

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)
  }
}

Upvotes: 4

vadian
vadian

Reputation: 285290

Definition in the Swift Language Reference

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.

Upvotes: 1

Related Questions