Home > Blockchain >  Passing types as an object in Swift
Passing types as an object in Swift

Time:02-25

Can a type be passed around as an object and used in a generic's type parameter?

func f0(any: Any) {
    let x = type(of: any)   // Can you pass around a type as an object?
    let y = Array<x>()      // Compile Error: cannot find type 'x' in scope
}

func f1(type: TypeObject) {     // I don't know what to put as a replacement for typeObject
    let y = Array<type>()       // Compile Error: cannot find type 'type' in scope
}

f1(type: Int.self)

I have no real-world application for this, I just want to see how Swift stacks up against other languages.

CodePudding user response:

Your first example can't work.

The second question requires metatype syntax.

func f1<T>(type: T.Type) {
  let y = [T]()
}
  • Related