Generics: optional conformance


(Jonathan Bailey) #1

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

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

    var delegate: T

    func logOut() {
        delegate.logOutPressed?()
    }
}

(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.


(Tim Vermeulen) #2

You could perhaps do something like

extension AccountView where T: LogOutDelegate {
    func logOut() {
        delegate?.logOutPressed()
    }
}

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

(delegate as? LogOutDelegate)?.logOutPressed()

(Jordan Rose) #3

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