Does type inference happen when using .init()?


let object: Class = Class()


let object: Class = .init()

To reduce the time for the compiler to infer the type, I specify the type of every property, constant and variable whenever possible.
By the way, does type inference happen for b) as well?
Is a) better than b) in terms of type inference?

a. No type inference. You already declare object is of type Class.
b. Yes type inference for .init(). It infers from the context that the object is a Class so it can get the init function from Class.

I realize you want to gain the performance by specifying the type. It's not worth it.
Swift compiler is getting better over time. so... :)) they make type inference happen for a reason.

Personally, I prefer reading it as

let object = Class()


let myColor = Color(...)

rather than

let myColor: Color = Color()


1 Like

IMO, it's about on par with old C's x++ vs ++x. That is, the amount of time you spend worrying would easily outdone any you could save by choosing the right version.

Whether there is any inference is quite debatable. The type-checker would still kick-in on both a) and b) to make sure everything has the correct type. Since the type .init is dictated by the type of object, b) isn't all that different from a). I doubt it's even noticeable.

Usually, I'd start annotating type when the compiler seems to struggle or when the expression starts to get complex/overlong. Otherwise, I'd just choose one that's easier to type:

let object = Class()

Thanks @Lantua @jonnguyen @tem

I don't use:

let object = Class()

This is because I set the function to display a warning when the type inference time exceeds 200ms.
I wondered if there was any difference between a) and b) that would affect the type inference time.

1 Like

If there's only one of those expression, I wouldn't worry too much about it. It may be the type checker booting up.