Generics: optional conformance

It would be really great if you could specify that a generic type might conform to a type.

protocol LogOutDelegate {
func logOutPressed()
class AccountView<T: DetailsDelegate? & LogOutDelegate?> {

    var delegate: T

    func logOut() {

(That was types directly in so forgive any errors)

At the moment I have different delegate variables (eg logOutDelegate detailsDelegate and it would be great to combine them into one.

You could perhaps do something like

extension AccountView where T: LogOutDelegate {
    func logOut() {

And if you always want the logOut function to be available, you could also consider implement it with

(delegate as? LogOutDelegate)?.logOutPressed()

This matches up nicely with some of @Douglas_Gregor's ideas in Conditionally further constrain a generic parameter: if <T: Constrained> { ... }.

1 Like