Nikita Ermolenko Nikita Ermolenko - 27 days ago 16
iOS Question

Type of Generic

Can I somehow check a type of

T
. I want to check that this type is
Array
or something else.

func request<T: Mappable>(completionHandler: (Result<T>) -> Void) {

}

Answer

One way to do this is to overload the method, like so:

private func request<T: Mappable>(isArray: Bool, completionHandler: (Result<T>) -> Void) {
  if isArray {
    print("is array")
  } else {
    print("is not array")
  }
}

func request<T>(completionHandler: (Result<Array<T>>) -> Void) {
  request(isArray: true, completionHandler: completionHandler)
}

func request<T: Mappable>(completionHandler: (Result<T>) -> Void) {
  request(isArray: false, completionHandler: completionHandler)
}

I'm assuming that somewhere you have defined:

extension Array: Mappable {}
Comments