Can I assign a default type to generic type T in Swift?

There’s no support for default generic arguments, but you can fake it by defining the default init() on a type-constrained extension, in which case the compiler will be smart enough to use that type. E.g.:

class MyManager<T> {
    let instance: T

    init(instance: T) {
        self.instance = instance
    }
}

extension MyManager where T == NSObject {
    convenience init() {
        self.init(instance: NSObject())
    }
}

And now you can initialize the type with no argument and it will default to MyManager<NSObject>:

let mm1 = MyManager(instance: "Foo") // MyManager<String>
let mm2 = MyManager(instance: 1) // MyManager<Int>
let mm3 = MyManager() // MyManager<NSObject>

SwiftUI uses this technique quite a lot.

Leave a Comment