How to Determine the Type of a Variable in Swift

How to determine the type of a variable in Swift

You can get a reference to the type object of a value by using the .dynamicType property. This is equivalent to Python's type() function, and is mentioned in the Swift documentation under Language Reference: Types: Metatype Type.

var intArray = [1, 2, 3]
let typeOfArray = intArray.dynamicType

With this type object, we are able to create a new instance of the same array type.

var newArray = typeOfArray()
newArray.append(5)
newArray.append(6)
println(newArray)
[5, 6]

We can see that this new value is of the same type ([Int]) by attempting to append a float:

newArray.append(1.5)
error: type 'Int' does not conform to protocol 'FloatLiteralConvertible'

If we import Cocoa and use an array literal with mixed types, we can see that an NSArray is created:

import Cocoa

var mixedArray = [1, "2"]
let mixedArrayType = mixedArray.dynamicType

var newArray = mixedArrayType()
var mutableArray = newArray.mutableCopy() as NSMutableArray

mutableArray.addObject(1)
mutableArray.addObject(1.5)
mutableArray.addObject("2")

println(mutableArray)
(1, "1.5", 2)

However, at this point there does not seem to be any general way to generate a string description of a type object, so this may not serve the debugging role that you were asking about.

Types derived from NSObject do have a .description() method, as is used in SiLo's answer,

println(mixedArrayType.description())
__NSArrayI

However this is not present on types such as Swift's built-in arrays.

println(typeOfArray.description())
error: '[Int].Type' does not have a member named 'description'

how to get type of a variable in swift

You can check the type of any variable using is keyword.

var a = 0
var b = "demo"
if (a is Int) {
print("It's an Int")
}

if (b is String) {
print("It's a String")
}

To compare any complex type, you can use below method:

if type(of: abc) == type(of: def) {
print("matching type")
} else {
print("something else")
}

How do I print the type or class of a variable in Swift?

Update September 2016

Swift 3.0: Use type(of:), e.g. type(of: someThing) (since the dynamicType keyword has been removed)

Update October 2015:

I updated the examples below to the new Swift 2.0 syntax (e.g. println was replaced with print, toString() is now String()).

From the Xcode 6.3 release notes:

@nschum points out in the comments that the Xcode 6.3 release notes show another way:

Type values now print as the full demangled type name when used with
println or string interpolation.

import Foundation

class PureSwiftClass { }

var myvar0 = NSString() // Objective-C class
var myvar1 = PureSwiftClass()
var myvar2 = 42
var myvar3 = "Hans"

print( "String(myvar0.dynamicType) -> \(myvar0.dynamicType)")
print( "String(myvar1.dynamicType) -> \(myvar1.dynamicType)")
print( "String(myvar2.dynamicType) -> \(myvar2.dynamicType)")
print( "String(myvar3.dynamicType) -> \(myvar3.dynamicType)")

print( "String(Int.self) -> \(Int.self)")
print( "String((Int?).self -> \((Int?).self)")
print( "String(NSString.self) -> \(NSString.self)")
print( "String(Array<String>.self) -> \(Array<String>.self)")

Which outputs:

String(myvar0.dynamicType) -> __NSCFConstantString
String(myvar1.dynamicType) -> PureSwiftClass
String(myvar2.dynamicType) -> Int
String(myvar3.dynamicType) -> String
String(Int.self) -> Int
String((Int?).self -> Optional<Int>
String(NSString.self) -> NSString
String(Array<String>.self) -> Array<String>

Update for Xcode 6.3:

You can use the _stdlib_getDemangledTypeName():

print( "TypeName0 = \(_stdlib_getDemangledTypeName(myvar0))")
print( "TypeName1 = \(_stdlib_getDemangledTypeName(myvar1))")
print( "TypeName2 = \(_stdlib_getDemangledTypeName(myvar2))")
print( "TypeName3 = \(_stdlib_getDemangledTypeName(myvar3))")

and get this as output:

TypeName0 = NSString
TypeName1 = __lldb_expr_26.PureSwiftClass
TypeName2 = Swift.Int
TypeName3 = Swift.String

Original answer:

Prior to Xcode 6.3 _stdlib_getTypeName got the mangled type name of a variable. Ewan Swick's blog entry helps to decipher these strings:

e.g. _TtSi stands for Swift's internal Int type.

Mike Ash has a great blog entry covering the same topic.

Checking if an object is a given type in Swift

If you want to check against a specific type you can do the following:

if let stringArray = obj as? [String] {
// obj is a string array. Do something with stringArray
}
else {
// obj is not a string array
}

You can use "as!" and that will throw a runtime error if obj is not of type [String]

let stringArray = obj as! [String]

You can also check one element at a time:

let items : [Any] = ["Hello", "World"]
for obj in items {
if let str = obj as? String {
// obj is a String. Do something with str
}
else {
// obj is not a String
}
}

How do you find out the type of an object (in Swift)?

Swift 3 version:

type(of: yourObject)

know type of variable in Swift

You were close with use of Mirror: you can look at the displayStyle property (of enum type Mirror.DisplayStyle) of the Mirror reflecting upon an instance of your type

struct Foo {}
class Bar {}

let foo = Foo()
let bar = Bar()

if let displayStyle = Mirror(reflecting: foo).displayStyle {
print(displayStyle) // struct
}

if let displayStyle = Mirror(reflecting: bar).displayStyle {
print(displayStyle) // class
}

Just note that .optional is also a case of the DisplayStyle enum of Mirror, so be sure to reflect on concrete (unwrapped) types:

struct Foo {}

let foo: Foo? = Foo()

if let displayStyle = Mirror(reflecting: foo as Any).displayStyle {
// 'as Any' to suppress warnings ...
print(displayStyle) // optional
}

how to check the type of a variable in swift

You can do this with the is operator.
Example code:

var test: AnyObject

test = 12.2

if test is Double {
println("Double type")
} else if test is Int {
println("Int type")
} else if test is Float {
println("Float type")
} else {
println("Unkown type")
}

According to Apple docs:

Checking Type

Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if
the instance is of that subclass type and false if it is not.

Check Type of Object ios swift

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"]

Sample Image

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:

Sample Image

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>

What is the right way to find the type of variables of `struct` type in Swift?

i personaly would use

if(x is Int)
{
print("\(x) is of type Int")
}

rather than using typeof if you're expecting x to be an integer as it's far more readable. but sure, you can use typeOf if you want to. Both are equally right

How to define a variable with multiple specific custom types ? (in Swift)

Seems like you need to use protocols.

Something like:

protocol CustomType {
// your definitions ...
}

extension String: CustomType {}
extension Int: CustomType {}

let customType1: CustomType = "string"
print(customType1)
let customType2: CustomType = 0
print(customType2)

// Error: Value of type 'Double' does not conform to specified type 'CustomType'
// let customType3: CustomType = 0.0

In this case, values of CustomType type will only accept String and Int types (because of the protocol conformance).



Related Topics



Leave a reply



Submit