Search code examples
iosswiftgenericsgeneric-programming

Access properties and methods of <T> from swift generic


I am not sure if this is possible or not but I think I have seen it before.

I am performing some validation on form objects throughout my app and I want a central, reusable way of doing this. I have come up with the following:

class RGOValidatedObject<T> {
    var validationPredicate: ((RGOValidatedObject<T>) -> Bool)?

    var isValid: Bool {
        return true
    }
}

I want to be able to access the properties and methods of T as if I was subclassing it directly, rather than adding a property to RGOValidatedObject to return the value of T. Consider the following:

RGOValidatedObject<String>().substringToIndex(1)

This is what I mean by access T's properties and methods on the RGOValidatedObject, almost as if I just subclassed T.

Is this possible? If so, how do I go about doing so? I am new to the concept of Swift generics but like the look of them.


Solution

  • No, there is no "lifting" syntax that would forward methods this way (though there have been several discussions about similar features in the future). You need to add a let value: T property to access it.

    A somewhat more common version of this problem is building an Observable<T>. You can't make that fully transparent in Swift, such that you could just call T methods on it (in the way that you can with KVO magic). It has to be explicit.