I have passed a parameter to a function of type AnyObject because anything can be passed to it. Is there a way to get the type of Object passed, dynamically?
Any and AnyObject are two special types in Swift that are used for working with non-specific types. According to Apple's Swift documentation, Any can represent an instance of any type at all, including function types and optional types. AnyObject can represent an instance of any class type.
You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.
Any can represent an instance of any type at all, including function types. AnyObject can represent an instance of any class type.
AnyObject is a protocol to which all classes implicitly conform. In fact, the standard library contains a type alias AnyClass representing AnyObject. Type . You can use AnyObject if you need the flexibility of an untyped object.
It's not clear what you mean by "the type" in your question. For any value of any type in Swift, you can get its dynamic runtime type like this:
theVariable.dynamicType
What you can do with it is another question.
Swift 3 version with @jojodmo's hint:
type(of: theVariable)
Typically this is what generics are for. There is seldom good reason for having an AnyObject
in code that doesn't interact with ObjC. If you're then performing different actions based on the type, then you probably actually meant to use overloading.
That said, there are several ways to get access to the type. Typically you want to run different code depending on the type, so you can use a switch
for that:
let x:AnyObject = "asdf"
switch x {
case is String: println("I'm a string")
default: println("I'm not a string")
}
or
let x:AnyObject = "asdf"
switch x {
case let xString as String: println("I'm a string: \(xString)")
default: println("I'm not a string")
}
Or you can use an if:
if let string = x as? String {
println("I'm a string: \(string)")
}
See "Type Casting for Any and AnyObject" in the Swift Programming Language for more discussion.
But again, unless you're working with ObjC code, there is seldom reason to use Any
or AnyObject
. Generics and overloads are the tools designed to solve those problems in Swift.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With