How to Find Out the Type of an Object (In Swift)

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

Swift 3 version:

type(of: yourObject)

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 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 the object type in Swift3

Expanding on @jglasse's answer, you can get the type of an object by using

let theType = type(of: someObject)

You can then get a string from that by

let typeString = String(describing: type)

Or in one line:

let typeString = String(describing: type(of: someObject))

how to get some data from the type any in swift

This is the string format you would get for an NSData. Assuming it really is an NSData, you would convert it to a Data. (And then, ideally, replace Any with Data in your definition. Any types a major pain to work with.)

if let data = machineNumber as? Data {
// use `data` for the bytes
}

Swift - Check if object is of a given type (where the type has been passed as function argument)

I don't know where you are taking myArray. You probably need to create an extension to Array for MyBaseClass. Like this:

extension Array where Element: MyBaseClass {
func myFilter<T: MyBaseClass>(objectType: T.Type) -> [T] {
var filteredArray: [T] = []
for object in self {
if let object = object as? T {
filteredArray.append(object)
}
}

return filteredArray
}
}

Then you can call:

// Example call
let array = [SubclassA(), SubclassA(), SubclassC(), SubclassD()]
array.myFilter(objectType: SubclassD.self) // == [SubclassD()]

EDIT:
Easy solution if you want a return type of myFilter to be just MyBaseClass and you don't want to change the original array would be this:

array.filter { $0 is SubclassD }

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



Related Topics



Leave a reply



Submit