Using a Type Variable in a Generic

前端 未结 5 1557
迷失自我
迷失自我 2020-11-29 03:20

I have this question except for Swift. How do I use a Type variable in a generic?

I tried this:

func intType() -> Int.Type {
    retu         


        
5条回答
  •  难免孤独
    2020-11-29 03:25

    There is a way and it's called generics. You could do something like that.

    class func foo() {
        test(Int.self)
    }
    
    class func test(t: T.Type) {
        var arr = Array()
    }
    

    You will need to hint the compiler at the type you want to specialize the function with, one way or another. Another way is with return param (discarded in that case):

    class func foo() {
        let _:Int = test()
    }
    
    class func test() -> T {
        var arr = Array()
    }
    

    And using generics on a class (or struct) you don't need the extra param:

    class Whatever {
        var array = [T]() // another way to init the array.
    }
    
    let we = Whatever()
    

提交回复
热议问题