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]
source share