错误:变量在其自身的初始值中与type(of :)函数一起使用

qua*_*kid 5 swift swift4.1

在Apple的Swift标准文档中

func printInfo(_ value: Any) {
   let type = type(of: value)
   print("'\(value)' of type '\(type)'")
}
Run Code Online (Sandbox Code Playgroud)

并给出错误:变量在其自己的初始值内使用

在此处输入图片说明

如何使用Swift 4.1修复此问题?

Cod*_*ent 4

这是一个文档错误。该功能曾经是typeOf. 最近的版本(不记得是哪一个)将其重命名为type. type编译器对局部变量和typeSwift 标准库中的函数感到困惑。

为局部变量使用不同的名称:

func printInfo(_ value: Any) {
   let t = type(of: value)
   print("'\(value)' of type '\(t)'")
}
Run Code Online (Sandbox Code Playgroud)

或者明确引用该函数:

func printInfo(_ value: Any) {
   let type = Swift.type(of: value)
   print("'\(value)' of type '\(type)'")
}
Run Code Online (Sandbox Code Playgroud)