Is there a way to print the runtime type of a variable in swift? For example:
var now = NSDate()
var soon = now.dateByAddingTimeInterval(5.0)
println("\(now.dynamicType)")
// Prints "(Metatype)"
println("\(now.dynamicType.description()")
// Prints "__NSDate" since objective-c Class objects have a "description" selector
println("\(soon.dynamicType.description()")
// Compile-time error since ImplicitlyUnwrappedOptional<NSDate> has no "description" method
In the example above, I'm looking for a way to show that the variable "soon" is of type ImplicitlyUnwrappedOptional<NSDate>
, or at least NSDate!
.
SWIFT 3
With the latest release of Swift 3 we can get pretty descriptions of type names through the
String
initializer. Like, for exampleprint(String(describing: type(of: object)))
. Whereobject
can be an instance variable like array, a dictionary, anInt
, aNSDate
, an instance of a custom class, etc.Here is my complete answer: Get class name of object as string in Swift
That question is looking for a way to getting the class name of an object as string but, also i proposed another way to getting the class name of a variable that isn't subclass of
NSObject
. Here it is:I made a static function which takes as parameter an object of type
Any
and returns its class name asString
:) .I tested this function with some variables like:
and the output was:
I've found a solution for self-developed classes (or such you have access to).
Place the following computed property within your objects class definition:
Now you can simply call the class name on your object like so:
Please note that this will only work if your class definition is made within a file that is named exactly like the class you want the name of.
As this is commonly the case the above answer should do it for most cases. But in some special cases you might need to figure out a different solution.
If you need the class name within the class (file) itself you can simply use this line:
Maybe this method helps some people out there.
In Swift 3.0, you can use
type(of:)
, asdynamicType
keyword has been removed.This is how you get a type string of your object or Type which is consistent and takes into account to which module the object definition belongs to or nested in. Works in Swift 4.x.
Not exactly what you are after, but you can also check the type of the variable against Swift types like so:
For example.
The top answer doesn't have a working example of the new way of doing this using
type(of:
. So to help rookies like me, here is a working example, taken mostly from Apple's docs here - https://developer.apple.com/documentation/swift/2885064-type