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!
.
In the latest XCode 6.3 with Swift 1.2, this is the only way I found:
Swift 3.0
Edit: A new
toString
function has been introduced in Swift 1.2 (Xcode 6.3).You can now print the demangled type of any type using
.self
and any instance using.dynamicType
:Try calling
YourClass.self
andyourObject.dynamicType
.Reference: https://devforums.apple.com/thread/227425.
You can use reflect to get information about object.
For example name of object class:
In Xcode 8, Swift 3.0
Steps:
1. Get the Type:
Option 1:
Option 2:
2. Convert Type to String: