Reputation:
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
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
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 String
s).
If the variable's type is implicitly inferred, we can get some information by ⌥ Option+clicking.
let test = ["Chicago", "New York", "Oregon", "Tampa"]
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:
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
Reputation: 7549
You can use is
in Swift.
if test is NSArray {
println("is NSArray")
}
Upvotes: 6