Rishi
Rishi

Reputation: 2037

Get the type of AnyObject dynamically in 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?

Upvotes: 15

Views: 13462

Answers (4)

newacct
newacct

Reputation: 122538

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)

Upvotes: 31

Supapon Pick Pucknavin
Supapon Pick Pucknavin

Reputation: 493

func testType(value:AnyObject!){

    if let v = value as? NSString{

        println("NSString")

    }else if let v = value as? NSNumber{

        println("NSNumber")

    }else if let v = value as? Double{

        println("Double")

    }else if let v = value as? Int{
        println("Int")
    }
}

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299663

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.

Upvotes: 13

Clement Bisaillon
Clement Bisaillon

Reputation: 5187

First import Foundation

and if you wan't the type of test1 do that:

var test1 = "test"

println(_stdlib_getTypeName(test1))

You will get "TtSS" TtSS mean String.

if you would try with a Int it would be TtSi (i for int)

Upvotes: 0

Related Questions