Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the type of AnyObject dynamically in Swift

Tags:

swift

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?

like image 976
Rishi Avatar asked Aug 27 '14 12:08

Rishi


People also ask

What is true about AnyObject data type in Swift?

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.

What is AnyObject Swift?

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.

Whats the difference between any and AnyObject?

Any can represent an instance of any type at all, including function types. AnyObject can represent an instance of any class type.

Is AnyObject a protocol?

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.


2 Answers

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)
like image 96
newacct Avatar answered Sep 22 '22 17:09

newacct


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.

like image 43
Rob Napier Avatar answered Sep 18 '22 17:09

Rob Napier