user5130344
user5130344

Reputation:

Check Type of Object ios swift

How do I check the type of object my variable is in ios swift?

For Example

let test= ["Chicago", "New York", "Oregon", "Tampa"]

is test NSArray? NSMutableArray? NSString?

I'm used to visual studio using an immediate window, can this be in debug mode in Xcode?

Upvotes: 8

Views: 11148

Answers (3)

mrabins
mrabins

Reputation: 197

type(of:)

Which Returns the dynamic type of a value.

func foo<T>(x: T) -> T.Type {
  return type(of: x)
}

Upvotes: 1

nhgrif
nhgrif

Reputation: 62052

There are several methods for determine an object's type at debug or compile time.


If the variable's type is explicitly declared, just look for it:

let test: [String] = ["Chicago", "New York", "Oregon", "Tampa"]

Here, test is clearly marked as a [String] (a Swift array of Strings).


If the variable's type is implicitly inferred, we can get some information by ⌥ Option+clicking.

let test = ["Chicago", "New York", "Oregon", "Tampa"]

enter image description here

Here, we can see test's type is [String].


We can print the object's type using dynamicType:

let test = ["Chicago", "New York", "Oregon", "Tampa"]

println(test.dynamicType)

Prints:

Swift.Array<Swift.String>

We can also see our variable in the variable's view:

enter image description here

Here, we can see the variable's type clearly in the parenthesis: [String]


Also, at a break point, we can ask the debugger about the variable:

(lldb) po test
["Chicago", "New York", "Oregon", "Tampa"]

(lldb) po test.dynamicType
Swift.Array<Swift.String>

Upvotes: 13

Shamas S
Shamas S

Reputation: 7549

You can use is in Swift.

if test is NSArray {
  println("is NSArray")
}

Upvotes: 6

Related Questions