【问题标题】:Typealias with structs带有结构的类型别名
【发布时间】:2014-06-05 20:54:59
【问题描述】:

是否可以在structs 或classes 中使用typealias?例如:

struct Foo {
    typealias type = Int
}

这编译没有错误。但是,当我使用这个结构时:

let f = new Foo
let bar: f.type

这给了我一个:

使用未声明的类型'f'

你如何检索这个存储的类型?

这对泛型结构很有用,例如:

struct TypeHolder<T> {
    typealias type = T
}

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

【问题讨论】:

    标签: generics swift


    【解决方案1】:

    是的,你可以这样做。

    你犯了两个小错误:

    • 不要使用new。
    • 使用类名访问类型,而不是实例。

    示例:

    struct Foo {
        typealias type = Int
    }
    
    let f = Foo()
    let bar: Foo.type = 5
    

    【讨论】:

    • 泛型可以做到这一点吗?
    • 是的,但是您必须输入Foo&lt;T&gt;.type,因此在这个简单的案例中不会保存任何输入。 :)
    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 2020-11-21
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多