是否有一种方法可以在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!
我目前的Xcode版本是6.0 (6A280e)。
import Foundation
class Person { var name: String; init(name: String) { self.name = name }}
class Patient: Person {}
class Doctor: Person {}
var variables:[Any] = [
5,
7.5,
true,
"maple",
Person(name:"Sarah"),
Patient(name:"Pat"),
Doctor(name:"Sandy")
]
for variable in variables {
let typeLongName = _stdlib_getDemangledTypeName(variable)
let tokens = split(typeLongName, { $0 == "." })
if let typeName = tokens.last {
println("Variable \(variable) is of Type \(typeName).")
}
}
输出:
Variable 5 is of Type Int.
Variable 7.5 is of Type Double.
Variable true is of Type Bool.
Variable maple is of Type String.
Variable Swift001.Person is of Type Person.
Variable Swift001.Patient is of Type Patient.
Variable Swift001.Doctor is of Type Doctor.
斯威夫特5
在Swift 3的最新版本中,我们可以通过String初始化器获得对类型名称的详细描述。例如,print(String(description: type(of: object)))。其中object可以是一个实例变量,如数组、字典、Int、NSDate、自定义类的实例等。
这是我的完整答案:在Swift中获取对象的类名作为字符串
这个问题是寻找一种方法来获得一个对象的类名作为字符串,但我也提出了另一种方法来获得一个变量的类名,这不是NSObject的子类。下面就是:
class Utility{
class func classNameAsString(obj: Any) -> String {
//prints more readable results for dictionaries, arrays, Int, etc
return String(describing: type(of: obj))
}
}
我做了一个静态函数,它以Any类型的对象作为参数,并返回其类名String:)。
我用一些变量测试了这个函数,比如:
let diccionary: [String: CGFloat] = [:]
let array: [Int] = []
let numInt = 9
let numFloat: CGFloat = 3.0
let numDouble: Double = 1.0
let classOne = ClassOne()
let classTwo: ClassTwo? = ClassTwo()
let now = NSDate()
let lbl = UILabel()
结果是:
Dictionary的类型为Dictionary
array的类型是array
numInt是Int类型
numFloat类型为CGFloat
numDouble是Double类型
classOne的类型为:classOne
classTwo的类型为:classTwo
now的类型是:日期
lbl类型为:UILabel