swift - 如何在 Swift 中打印变量的类型或类?

标签 swift types

有没有办法在 swift 中打印变量的运行时类型?例如:

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

在上面的示例中,我正在寻找一种方法来表明变量“soon”的类型为 ImplicitlyUnwrappedOptional<NSDate> , 或至少 NSDate! .

最佳答案

2016 年 9 月更新

Swift 3.0:使用 type(of:),例如type(of: someThing)(因为 dynamicType 关键字已被删除)

2015 年 10 月更新:

我将下面的示例更新为新的 Swift 2.0 语法(例如 println 被替换为 printtoString() 现在是 String()).

来自 Xcode 6.3 发行说明:

@nschum 在评论中指出 Xcode 6.3 release notes换种方式展示:

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

哪些输出:

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>

Xcode 6.3 更新:

您可以使用 _stdlib_getDemangledTypeName():

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

并将其作为输出:

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

原始答案:

在 Xcode 6.3 之前 _stdlib_getTypeName 获取变量的错位类型名称。 Ewan Swick's blog entry有助于破译这些字符串:

例如_TtSi 代表 Swift 内部的 Int 类型。

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

关于swift - 如何在 Swift 中打印变量的类型或类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24006165/

相关文章:

types - 当 GADT 构造函数包含多个类型变量时,局部抽象类型的范围错误

c++ - QVariant 中的自定义类型转换为空字符串

swift - 使用组合时的代码共享

ios - 有没有一种好方法可以为您的 iOS 应用程序测试不同时区?

swift - 在 iPad 上使用 SwiftUI NavigationView 在代码中切换侧边栏

Java >>>= 运算符

ios - 在快速构建 UISlider 时发送到实例的无法识别的选择器

swift - 声明符合协议(protocol)的类数组

java - Kotlin 传入实现参数化接口(interface)的类型

mysql - 存储 01 和 10 的 SQL 数据类型