Default value of template T

Does Swift has the syntax that lets me get the default value of a template type T, like below:

struct VarLock<T> {
    private var v = default(T) // or T()
}

Accepted Reply

protocol VT {
    init()
}
struct VarType<T: VT> {
    var item: T = T()
}

Replies

protocol VT {
    init()
}
struct VarType<T: VT> {
    var item: T = T()
}

Expanding on this, you need to understand that Swift generics are very different from C++ templates. C++ templates are more like mega macros: Every time you instantiate one, the compiler creates a new copy of that code that’s specialised for the type parameters. This has a couple of important consequences:

  • You can end up with a lot of compiled instantiations of the same code.

  • By default the compiler checks the instantiation’s code at time of use, not the template at time of declaration.

[Please note that the above is a wild simplification based on someone who knows very little about C++ (-: ]

In contrast, Swift generic code:

  • Is compiled directly

  • May be specialised, but that’s considered an optimisation

This means that the generic code must ‘know’ about the types over which it’s generic. Your code fails because VarLock doesn’t know that T has a non-argument initialiser. MobileTen’s code works because the VT constraint tells the compiler this.

These constraints are similar to C++ template constraints [1] but, again, generics and templates are very different things and, if you’re coming from a C++ background, you need to wrap your head around that before generics will make any sense.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] And the related concept of… well… concepts:

https://en.cppreference.com/w/cpp/language/constraints