简体   繁体   中英

Swift - Declaring an array of generics

I am struggling creating an array of generics in Swift. Here are my protocols / classes.

public protocol InitializableWithData {
    init(data: NSData?) throws 
}

internal struct RequestWithCompletionHandler<T: InitializableWithData> {
    let request: APIRequest<T>
    let completionHandler: ((response: APIResponse<T>?, error: Error?) -> Void)?
}

var ongoingRequests = [RequestWithCompletionHandler<InitializableWithData>]()

I get the following error:

Using InitializableWithData as a concrete type conforming to protocol 'InitializableWithData' is not supported.

I am not interested in the actual type "contained" by RequestWithCompletionHandler . I just want to keep track of all requests, without caring what entity they will "return". I want to keep track of them so I can cancel them, pause them, etc.

So I want to keep track of all the ongoing requests so I can re execute them if necessary.

The error message says you cannot use a protocol type ( InitializableWithData ) as concrete type (in RequestWithCompletionHandler<InitializableWithData> ).

You need a concrete type conforming to the protocol like a struct for example

public protocol InitializableWithData {
  init(data: NSData?) throws
}

internal struct RequestWithCompletionHandler<T: InitializableWithData> {
  let request: APIRequest<T>
  let completionHandler: ((response: APIResponse<T>?, error: Error?) -> Void)?
}

struct Test : InitializableWithData {
  let data : NSData?

  init(data: NSData?) throws {
    self.data = data
  }
}

var ongoingRequests = [RequestWithCompletionHandler<Test>]()

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