Let type = ... and type(of: ...)

I wrote:
let type = "_SomeService._tcp."
and all was fine.

A week later I tried to use:
let className = type(of: someThing)
and got a confusing error message about a String. (someThing was definitely not a String)

It took me quite a while to remember the "let type" line.
All became normal again when I changed this line to:
let serviceType = "_SomeService._tcp."

Should there be a compiler-warning like: "The name 'type' might clash with 'type(of:)'" ?


When posting something like this, it's good to provide a reproducible example that's self contained and syntax-highlighted, like

let type = "some value"
let something = 1
let typeOfSomething = type(of: something) // ❌ error: cannot call value of non-function type 'String'

Also, className is an misleading and wrong name for the variable. It's storing a metatype object, not name (which would make people think it's a String; it's not).

Such clashes are possible with pretty much all standard library types, functions and methods. They can be disambiguated by explicitly qualifying the module name:

let type = "some value"	
let something = 1
let typeOfSomething = Swift.type(of: something) // => Int

You see this often when trying to use max in an array extension, where you inadvertently reference the instance method Array.max rather than the global function Swift.max.

Terms of Service

Privacy Policy

Cookie Policy