Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error : Variable used within its own initial value with type(of:) function

Tags:

swift

swift4.1

In Swift standard document by Apple :

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

and it give an error : Variable used within its own initial value

enter image description here

How can I fix this with Swift 4.1?

like image 419
quangkid Avatar asked May 03 '18 03:05

quangkid


1 Answers

That's a documentation error. The function used to be typeOf. Recent version (can't remember which one) renamed it to type. The compiler is getting confused between type the local variable and type the function in Swift's Standard Library.

Use a different name for your local variable:

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

Or explicitly refer to the function:

func printInfo(_ value: Any) {
   let type = Swift.type(of: value)
   print("'\(value)' of type '\(type)'")
}
like image 65
Code Different Avatar answered Oct 06 '22 00:10

Code Different