Generics call with Type T in Swift

后端 未结 7 992
逝去的感伤
逝去的感伤 2021-02-12 17:14

In my application I want to create an generic method which creates an array of object depening on the given type T.

I created the following function:

fun         


        
7条回答
  •  深忆病人
    2021-02-12 18:18

    I worked around this by borrowing from the swift runtime function unsafeBitCast.

    It's declared as func unsafeBitCast(x: T, _: U.Type) -> U and you can call it as unsafeBitCast(value, MyType).

    Applied to your function this would be

    func getArray(key:String, _: T.Type) -> T[] {
        // function stays the same
    }
    

    And you can call it like this

    getArray("key", Document)
    

提交回复
热议问题