Perhaps you want to look at Mirror
which allows a degree of introspection. Documentation is here
import Foundation
func prettyPrint(_ any: Any) -> String {
let m = Mirror(reflecting: any)
switch m.displayStyle {
case .some(.class): // ****
return "Class"
case .some(.collection):
return "Collection, \(m.children.count) elements"
case .some(.tuple):
return "Tuple, \(m.children.count) elements"
case .some(.dictionary):
return "Dictionary, \(m.children.count) elements"
case .some(.set):
return "Set, \(m.children.count) elements"
case .some(.optional):
return "Optional"
case .some(.enum):
return "Enum"
case .some(.struct):
return "Struct"
default:
return "\(String(describing: m.displayStyle))"
}
}
class A {}
prettyPrint([1, 2, 3]) // "Collection, 3 elements"
prettyPrint(Set<String>()) // "Set, 0 elements"
prettyPrint([1: 2, 3: 4]) // "Dictionary, 2 elements"
prettyPrint((1, 2, 3)) // "Tuple, 3 elements"
prettyPrint(3) // "nil"
prettyPrint("3") // "nil"
prettyPrint(NSObject()) // "Class"
prettyPrint(NSArray(array:[1, 2, 3])) // "Collection, 3 elements"
prettyPrint(A()) // "Class"
// prettyPrint(nil) // Compile time error "Nil is not compatible with Any