-3

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.

Yogurt
  • 2,913
  • 2
  • 32
  • 63
  • Yes, but the type has to be known at compile time. Just think about it. How would `y.append` work? What kind of parameter would it accept? The compiler *has* to know the type. – Sulthan Feb 24 '22 at 21:24
  • @Sulthan could you make an example – Reza Khonsari Feb 24 '22 at 21:40
  • 1
    "Can a type be passed around as an object?" Absolutely (well, as a value). Can that be "used in a generic's type parameter?" No. What strongly-typed language with generic types are you thinking of where this is possible? – Rob Napier Feb 24 '22 at 21:40
  • 1
    @RezaKhonsari Sultan's example is `let y = Array(); y.append(...what could possibly go here?...)`. How would you make anything other than an empty array? – Rob Napier Feb 24 '22 at 21:42
  • Try following this: [Swift Generics](https://docs.swift.org/swift-book/LanguageGuide/Generics.html) – HunterLion Feb 24 '22 at 21:47
  • @Sulthan The user Jessy understood the question. You can take a look at his answer to understand what I was asking. – Yogurt Feb 24 '22 at 23:57
  • @RobNapier I think you guys went off on a tangent with the array thing. You can look at Jessy's answer to learn what I was getting at. – Yogurt Feb 25 '22 at 00:07

1 Answers1

2

Your first example can't work*

The second question requires metatype syntax.

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

* It's only a problem with trying to discern type information that wasn't there to begin with. If you have that, you can use type(of: any), but it won't have a benefit over T.self.

func f0<T>(any: T) {
  let x = type(of: any)
  let y = Array(x)
}

extension Array {
  init(_: Element.Type) {
    self = []
  }
}
  • 1
    Thanks for answering my useless question. People were twisting themselves into knots in the comments. Anyways, in the documentation, it says type(of:) returns the dynamic type, while T.Type returns the concrete meta-type. It seems like the meta-type can be passed around in the parameters of a function, but what can you use the dynamic type for? – Yogurt Feb 25 '22 at 21:37
  • 1
    Is this enough info? https://stackoverflow.com/questions/42037852/why-do-self-and-self-sometimes-refer-to-different-types-in-static-functions –  Feb 26 '22 at 00:22