yizzlez
yizzlez

Reputation: 8805

Typealias with structs

Is it possible to use typealias in structs or classes? For example:

struct Foo {
    typealias type = Int
}

This compiles without error. However, when I use this struct:

let f = new Foo
let bar: f.type

This gives me a:

Use of undeclared type 'f'

How can you retrieve this stored type?

This would be useful with generic structs, for example:

struct TypeHolder<T> {
    typealias type = T
}

let type1 = new TypeHolder<Int>
let fooint: type1.type

Upvotes: 1

Views: 934

Answers (1)

nschum
nschum

Reputation: 15422

Yes, you can do that.

You're making two small mistakes:

  • Don't use new.
  • Access the type using the class name, not the instance.

Example:

struct Foo {
    typealias type = Int
}

let f = Foo()
let bar: Foo.type = 5

Upvotes: 2

Related Questions