0

I want to create a protocol and extension which I will use in three different view controllers for API loading.

protocol WebAPILoader {

    // URL of remote resource
    var url: URL? { get set }

    // Array supposed to store loaded data.    
    associatedtype T
    var data: [T] { get set }

    // Function loading them
    func loadNextPage()
}

Every VC downloads different data using its endpoint so I want my function to choose which endpoint to use based on data type, like this:

extension WebAPILoader {

    mutating func loadNextPage() {

        guard let url = self.nextURL else {
            return
        }

        let dataType = type(of: data)
        var endpointLoader: ((URL?, @escaping (dataType? ,URL?, Error?) -> Void) -> ())? = nil

        switch data {
        case is [DataType1]:
            endpointLoader = DataType1().getData

        // Other cases...

        default:
            return
        }


        // EndpointLoader usage...
    } 
}

But Xcode keeps telling me various errors forbidding me from use of T as a Type in my extension. Is there any way of achieving that?

Jack Lawrence
  • 10,664
  • 1
  • 47
  • 61
cap-slow
  • 71
  • 1
  • 8
  • Huh, that's weird – the compiler doesn't like switching over a `[T]` with a conditional type casting pattern to some other array type. I would say that's a bug, given that `if let data = data as? [DataType1] {...}` works just fine. Feel free to [file a bug report](https://bugs.swift.org). – Hamish Mar 14 '17 at 21:51
  • Although note that your default implementation of `loadNextPage()` is `mutating`, which is incompatible with your non-mutating protocol requirement. You need to make them either both mutating or non mutating. – Hamish Mar 14 '17 at 21:52

0 Answers0