How to check the type of a universal class - an array?

I want to check if the generic class type is an array:

func test<T>() -> Wrapper<T> { let isArray = T.self is Array<Any> ... } 

But he warns

Passing from "T.type" to an unrelated type of "Array" always fails

How can I solve this problem?

Added: I uploaded my codes to Gist. https://gist.github.com/nallwhy/6dca541a2d1d468e0be03c97add384de

What I want to do is parse the json response according to it as an array of a model or just one model.

+6
source share
2 answers

As @Holex commentator says, you can use Any . Combine it with Mirror , and you can, for example, do something like this:

 func isItACollection(_ any: Any) -> [String : Any.Type]? { let m = Mirror(reflecting: any) switch m.displayStyle { case .some(.collection): print("Collection, \(m.children.count) elements \(m.subjectType)") var types: [String: Any.Type] = [:] for (_, t) in m.children { types["\(type(of: t))"] = type(of: t) } return types default: // Others are .Struct, .Class, .Enum print("Not a collection") return nil } } func test(_ a: Any) -> String { switch isItACollection(a) { case .some(let X): return "The argument is an array of \(X)" default: return "The argument is not an array" } } test([1, 2, 3]) // The argument is an array of ["Int": Swift.Int] test([1, 2, "3"]) // The argument is an array of ["Int": Swift.Int, "String": Swift.String] test(["1", "2", "3"]) // The argument is an array of ["String": Swift.String] test(Set<String>()) // The argument is not an array test([1: 2, 3: 4]) // The argument is not an array test((1, 2, 3)) // The argument is not an array test(3) // The argument is not an array test("3") // The argument is not an array test(NSObject()) // The argument is not an array test(NSArray(array:[1, 2, 3])) // The argument is an array of ["_SwiftTypePreservingNSNumber": _SwiftTypePreservingNSNumber] 
+2
source

You are not passing any arguments, so there is no type, and a generic function does not make sense. Remove the generic type:

 func() {} 

or, if you want to pass an argument:

 let array = ["test", "test"] func test<T>(argument: T) { let isArray = argument is Array<Any> print(isArray) } test(argument: array) 

Fingerprints: true

-one
source

Source: https://habr.com/ru/post/1013856/


All Articles