如何在 Swift 中获取对象的类名字符串?
大家好!我是 Swift 新手,正在尝试理解如何获取对象的类名字符串。在 Objective-C 中,我使用了 `NSStringFromClass([self class])`,但在 Swift 中这不起作用。
我需要在运行时记录对象类型以进行调试。例如,我有一个协议 `Animal` 和几个实现它的结构体:`Dog`、`Cat` 和 `Bird`。在函数 `printAnimalType(animal: Animal)` 中,我想输出传入的具体类型名称,而不仅仅是 "Animal"。
以下是我的代码示例:
```swift
protocol Animal {
func makeSound()
}
struct Dog: Animal {
func makeSound() { print("Woof!") }
}
struct Cat: Animal {
func makeSound() { print("Meow!") }
}
func printAnimalType(animal: Animal) {
// 如何在这里获取字符串 "Dog" 或 "Cat"?
print("Animal type: \(animal.self)")
}
```
我尝试过 `String(describing: animal.self)`,但它返回的是类似 `Animal` 或 `Dog` 的内容?不确定。还听说过 `Mirror` 和 `type(o`