Swift type inference

I wonder how swift type inference works under the hood?
let's say that we have a Var with type Int that the compiler had inferred successfully to its type, How the compiler exactly know that the Var is actually holds a number?

For initializing a value of types like Int and String via a literal, I believe the compiler parses the literal first, then initialize a value based on what the default type for the literal is. e.g. typealias FloatLiteralType = Double, typealias StringLiteralType = String. @xwu wrote some very good notes on type inference for numeric types.

For type inference at other places, e.g. inferencing the type of a closure's inputs or return value, the compiler looks for available type information and deduces what the missing information is. I don't exactly know how the compiler's type system works it out, though.


There is a WWDC 2020 talk on this topic by @hborla: https://developer.apple.com/videos/play/wwdc2020/10165/.

Terms of Service

Privacy Policy

Cookie Policy