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

2019-01-01 09:47发布

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 types
30条回答
人间绝色
2楼-- · 2019-01-01 10:14

In the latest XCode 6.3 with Swift 1.2, this is the only way I found:

if view.classForCoder.description() == "UISegment" {
    ...
}
查看更多
看淡一切
3楼-- · 2019-01-01 10:15

Swift 3.0

let string = "Hello"
let stringArray = ["one", "two"]
let dictionary = ["key": 2]

print(type(of: string)) // "String"

// Get type name as a string
String(describing: type(of: string)) // "String"
String(describing: type(of: stringArray)) // "Array<String>"
String(describing: type(of: dictionary)) // "Dictionary<String, Int>"

// Get full type as a string
String(reflecting: type(of: string)) // "Swift.String"
String(reflecting: type(of: stringArray)) // "Swift.Array<Swift.String>"
String(reflecting: type(of: dictionary)) // "Swift.Dictionary<Swift.String, Swift.Int>"
查看更多
人气声优
4楼-- · 2019-01-01 10:16

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:

struct Box<T> {}

toString("foo".dynamicType)            // Swift.String
toString([1, 23, 456].dynamicType)     // Swift.Array<Swift.Int>
toString((7 as NSNumber).dynamicType)  // __NSCFNumber

toString((Bool?).self)                 // Swift.Optional<Swift.Bool>
toString(Box<SinkOf<Character>>.self)  // __lldb_expr_1.Box<Swift.SinkOf<Swift.Character>>
toString(NSStream.self)                // NSStream

Try calling YourClass.self and yourObject.dynamicType.

Reference: https://devforums.apple.com/thread/227425.

查看更多
临风纵饮
5楼-- · 2019-01-01 10:16

You can use reflect to get information about object.
For example name of object class:

var classname = reflect(now).summary
查看更多
一个人的天荒地老
6楼-- · 2019-01-01 10:16
let i: Int = 20


  func getTypeName(v: Any) -> String {
    let fullName = _stdlib_demangleName(_stdlib_getTypeName(i))
    if let range = fullName.rangeOfString(".") {
        return fullName.substringFromIndex(range.endIndex)
    }
    return fullName
}

println("Var type is \(getTypeName(i)) = \(i)")
查看更多
余欢
7楼-- · 2019-01-01 10:17

In Xcode 8, Swift 3.0

Steps:

1. Get the Type:

Option 1:

let type : Type = MyClass.self  //Determines Type from Class

Option 2:

let type : Type = type(of:self) //Determines Type from self

2. Convert Type to String:

let string : String = "\(type)" //String
查看更多
登录 后发表回答