user1282993
user1282993

Reputation:

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?

Upvotes: 0

Views: 2325

Answers (1)

Adam Wright
Adam Wright

Reputation: 49376

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

Upvotes: 0

Related Questions