6

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
quangkid
  • 1,287
  • 1
  • 12
  • 31

1 Answers1

4

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)'")
}
Code Different
  • 90,614
  • 16
  • 144
  • 163