是否有一种方法可以在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.

其他回答

在Xcode 8, Swift 3.0

步骤:

1. 获取类型:

选项1:

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

选项2:

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

2. 转换类型为字符串:

let string : String = "\(type)" //String

Xcode 7.3.1, Swift 2.2:

字符串(instanceToPrint.self) .componentsSeparatedByString .last(“。”)

上面的答案没有使用type(of:的新方法的工作示例。所以为了帮助像我这样的新手,这里有一个工作的例子,主要来自苹果的文档- https://developer.apple.com/documentation/swift/2885064-type

doubleNum = 30.1

func printInfo(_ value: Any) {
    let varType = type(of: value)
    print("'\(value)' of type '\(varType)'")
}

printInfo(doubleNum)
//'30.1' of type 'Double'

斯威夫特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

Swift 3.0, Xcode 8

使用下面的代码,您可以向实例请求其类。你也可以比较两个实例,是否具有相同的类。

// CREATE pure SWIFT class
class MySwiftClass {
    var someString : String = "default"
    var someInt    : Int = 5
}

// CREATE instances
let firstInstance = MySwiftClass()
let secondInstance = MySwiftClass()
secondInstance.someString = "Donald"
secondInstance.someInt = 24

// INSPECT instances
if type(of: firstInstance) === MySwiftClass.self {
    print("SUCCESS with ===")
} else {
    print("PROBLEM with ===")
}

if type(of: firstInstance) == MySwiftClass.self {
    print("SUCCESS with ==")
} else {
    print("PROBLEM with ==")
}

// COMPARE CLASS OF TWO INSTANCES
if type(of: firstInstance) === type(of: secondInstance) {
    print("instances have equal class")
} else {
    print("instances have NOT equal class")
}