Can I write this function without having to pass an instance?

class A {
    static var identifier: String { String(describing: Self.self) }

    required init() { }

class B: A { }

class C: A { }

func accessStaticVarAndInitialize<T: A>(_: T) -> T {
    return T() as! T

let a = accessStaticVarAndInitialize(A()) // prints "A", returns instance of A
let b = accessStaticVarAndInitialize(B()) // prints "B", returns instance of B
let c = accessStaticVarAndInitialize(C()) // prints "C", returns instance of C

Is it possible to rewrite accessStaticVarAndInitialize(_:) in a way that allows me to give it only the (meta-)type of A, B, or C (i.e. A.Type, etc.), without having to instantiate anything just to resolve T?

Use T.Type instead of T and then use A.self etc. to specify the type when calling the function.

func accessStaticVarAndInitialize<T: A>(_: T.Type) -> T {
    return T()

let a = accessStaticVarAndInitialize(A.self) // prints "A", returns instance of A
let b = accessStaticVarAndInitialize(B.self) // prints "B", returns instance of B
let c = accessStaticVarAndInitialize(C.self) // prints "C", returns instance of C

Make the function parameter have type T.Type.

Also you don’t need the β€œas! T” cast, you can simply write return T().


Indeed, the as! T was a remnant of the actual implementation which is more complex than this reduced example here, and doesn't directly access the initializer.

Thank you both, @MarSe32m and @Nevin! :slight_smile:

Terms of Service

Privacy Policy

Cookie Policy