lyptt lyptt - 6 months ago 20
Swift Question

Swift: Return class constrained with generic type

I have a basic generic class:

class SharedClass<T> {}


And a builder for it:

class SharedClassBuilder {
func build<T>() -> SharedClass<T>? {
return ...
}
}


What I want to be able to do, is return an instance that inherits
SharedClass
, and conforms to
T
. For example:

protocol MyObject {
func doIt()
}

var result: SharedClass<MyObject>? = SharedClassBuilder().build()
result?.doIt()


Unfortunately, the Swift compiler complains that the returned type does not have a member named
doIt
.

Is there a way to achieve what I'm looking for?

Answer

I suspect it's not so much that you want the returned class to be constrained by the generic type, as you're asking the returned class to be an instance of the constrained type. In your snippet, you're expecting the unwrapped result to conform to MyObject. Taking this a step further, it means that the conformance of SharedClass is determined entirely from how it was constructed. As far as I know this isn't supported in Swift.

However, there's nothing stopping you having a member of SharedClass that is a T. Something along the lines of:

class SharedClass<T>  {
    var v : T?
}

class SharedClassBuilder {
    func build<T>() -> SharedClass<T>? {
        return SharedClass()
    }
}

protocol MyObject {
    func doIt()
}

var result: SharedClass<MyObject>? = SharedClassBuilder().build()
result?.v?.doIt()
Comments