8

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?

nhgrif
  • 61,578
  • 25
  • 134
  • 173
  • Answered here: http://stackoverflow.com/questions/24093433/how-to-determine-the-type-of-a-variable-in-swift – sashab Jul 19 '15 at 23:13

3 Answers3

13

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>
nhgrif
  • 61,578
  • 25
  • 134
  • 173
6

You can use is in Swift.

if test is NSArray {
  println("is NSArray")
}
Shamas S
  • 7,507
  • 10
  • 46
  • 58
  • problem is i dont know the variable type and would like to avoid inserting multiple if statements . Can I just check the variable type while I step through the code in debug mode? if so, is there an immediate window in xcode? –  Jul 19 '15 at 23:15
  • @DevTonio In xCode console, you can printout the values for variables by `po test`. It will print the information about the object there. – Shamas S Jul 19 '15 at 23:18
1
type(of:)

Which Returns the dynamic type of a value.

func foo<T>(x: T) -> T.Type {
  return type(of: x)
}
mrabins
  • 197
  • 1
  • 2
  • 10