简体   繁体   中英

Swift: cast generic type to protocol

Is there a way to tell the compiler that a generic type will conform with certain protocol at runtime?

The compiler can't know it, but I know it, and because of that I am able to prevent users of my library from having to specify the conforming type.

public extension Observable {
    public func cache(provider : Provider) -> Observable<E> {
        return cacheInternal(provider) // error: Type 'Element' does not conform to protocol 'Mappable'
    }

    internal func cacheInternal<T : Mappable>(provider : Provider) -> Observable<T> {
        //implementation
    }

    //what I want to avoid
    public func cache<T : Mappable>(type: T.Type, provider : Provider) -> Observable<E> {
        //implementation
    }
}

And I can't modify the generic type 'Element (E)' to conform with Mappable protocol because Observable is a class which I'm just extending.

Thanks!

Conditional protocol conformance could be the solution for you.

Since your cacheInternal(provider:) function needs the conformance to the Mappable protocol, this function should only be extended for of the type Observable with a generic type E that conforms to Mappable . This can be achieved with a where -clause in the extension declaration:

public extension Observable where E: Mappable {
    public func cache(provider : Provider) -> Observable<E> {
        return cacheInternal(provider)
    }

    internal func cacheInternal<T: Mappable>(_ provider : Provider) -> Observable<T> {
        //implementation
        return Observable<T>() //added this to silence the error that nothing is returned. Don't know, what exactly you want to return
    }
}

Footnote: I've updated the code to Swift 3 in order to test it correctly. (can't test on 2.x at the moment) I guess it was just the _ in cacheInternal to hide the argument label.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM