简体   繁体   中英

Pass Swift protocol as argument of another protocol function

I am creating generic data structure for my API result handling, reading about it online I found out that it would be best to use protocols and associatedtypes. This is my implementation so far.

protocol CreateDataCallback {
    associatedtype E
    func onSuccess(e:E) -> Void
    func onFail() -> Void
}

protocol DataSource: class {
    associatedtype T
    func getData<GDC:GetDataCallback>(id:ID, callback:GDC) -> Void 
}

As you can see in the code snippet, my getData function is not written correctly. Problem is that I don't know how to pass 'associatedtype T' from DataSource protocol to 'associatedtype E' of the CreateDataCallback protocol. I could write an extension of protocol DataSource but then it wouldn't be generic. Is this even possible in swift (I now that it is possible in Java), and if it is can you please shown me how. Thx

I'd make GDC an associated type of DataSource and I'd make GDC conform to CreateDataCallBack . Then you don't need associated type T, you can just refer to GDC.E

protocol DataSource: class{
    associatedtype GDC: CreateDataCallback
    func getData(id:GDC.E, callback:GDC) -> Void
}

Here's some implementations of the two protocols:

class Bar: CreateDataCallback
{
    func onSuccess(e: Int) {
        // code
    }

    func onFail() {
        // code
    }
    typealias E = Int
}

class Foo: DataSource
{
    typealias GDC = Bar // This makes GDC.E a typealias for Int

    func getData(id: Int, callback: Bar) {
        // code
    }
}

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