typealias of generic class in Swift

前端 未结 3 1838
孤城傲影
孤城傲影 2021-02-19 04:29

I am trying to make a typealias of a generic type class as follows

class Cars {
  ...
}

typealias SportCars = Cars

but I am getting a

3条回答
  •  臣服心动
    2021-02-19 05:27

    Right now, you can't do this with generics, as you've discovered.

    typealias Foo = Array
    // Doesn't work: Reference to generic type 'Array' requires argument in <...>
    

    The Swift Programming Language iBook chapter "Type Alias Declaration" doesn't actually state anything about which types cannot be aliased. But it simply looks like that partial types (like generics without placeholders specified) are not allowed.

    If you feel that this something Swift should do, file a Radar (bugreport) with Apple.

    While researching for this answer, I noticed that the partial type problem not only affects typealias but is visible elsewhere as well:

    let foo = Array.self
    // Doesn't work: Cannot convert the expression's type 'Array.Type' to type 'Array.Type'
    // … which is a very confusing error.
    
    var bar: Array.Type
    // Doesn't work: Reference to generic type 'Array' requires arguments in <...>
    
    let bar: Array.Type = Array.self
    // …/usr/bin/swift: Segmentation fault! :-)
    

    All of these work if you specify the placeholder types:

    typealias Foo = Array // Works
    let foo = Array.self // Works
    

提交回复
热议问题