Swift Type Inference: How Literals, Closures and Generics Get Types

Swift type inference is the compiler working out the type of every constant, variable and expression from clues in your code, at compile time. A literal with no other clue gets a default type: whole numbers become Int, decimals Double, text String. Otherwise the type comes from the initializer, the function being called or an annotation. The compiler solves a whole statement at once, which is why let x = 1 + 2.0 is a Double, but it never looks at later lines, which is why [] and nil need a written type. Below: how the compiler reaches each answer, how closures and generics are inferred, why some expressions are "too complex to type-check in reasonable time", and where inference stops.

Difficulty: Intermediate

Helpful to know first: how let and var declare values, the basic types Int, Double and String, and what a closure looks like.

How the Swift Compiler Infers a Type From Clues

Every value in Swift has exactly one type, fixed before the program runs. When you leave the type out, the compiler does not guess at run time. It collects clues, called constraints, and solves them while it builds your code:

  • Literals say what they can become. 42 can be any type that conforms to ExpressibleByIntegerLiteral: Int, Double, UInt8 and others.
  • Operators and functions say what they accept. The numeric + functions take two values of the same type and return that type.
  • The context says what it expects. A type annotation, a parameter type or a return type.

If exactly one choice satisfies every clue, that is the type. If several work, the compiler prefers the one that uses each literal's default type. You can see the result with type(of:), or by Option-clicking a name in Xcode.

Swift
let count = 42
let price = 9.99
let title = "Swift"
let isDone = false
print(type(of: count), type(of: price), type(of: title), type(of: isDone))
// Output: Int Double String Bool
Output✓ Tested · Swift 6.4
Int Double String Bool

None of these declarations names a type, yet all four are as fixed as if you had written : Int and so on. Assigning a String to count later fails with cannot assign value of type 'String' to type 'Int'. Inference saves typing; it does not make Swift dynamically typed.

The default type of each kind of literal

A default is used only when nothing else in the statement asks for a different type. The Swift data types article describes the types themselves.

Literal Default type Can also become, with a clue
42, 0xFF, 1_000 Int Double, Float, UInt8, Int64, any ExpressibleByIntegerLiteral type
3.14, 1e3 Double Float, any ExpressibleByFloatLiteral type
"text" String Character (one character only), Substring, StaticString
true, false Bool any ExpressibleByBooleanLiteral type
[1, 2] Array Set, any ExpressibleByArrayLiteral type
["a": 1] Dictionary KeyValuePairs, any ExpressibleByDictionaryLiteral type
nil none any optional type, but only when the context names it

1e3 has an exponent, so it is a floating-point literal: its value is the Double 1000.0, not the Int 1000.

Why let x = 1 + 2.0 Is a Double

This line surprises people who know that Swift never converts an Int to a Double by itself. The key is that 1 is not an Int yet. It is an integer literal, and an integer literal can become a Double.

The compiler solves the whole statement together. + needs both sides to have the same type. 2.0 cannot be an Int, so Int is ruled out. Double fits both literals and is the default for 2.0, so the answer is Double + Double.

Swift
let total = 1 + 2.0
print(type(of: total), total)

let mean = (3 + 4) / 2.0
print(mean)
// Output:
// Double 3.0
// 3.5
Output✓ Tested · Swift 6.4
Double 3.0
3.5

The parentheses in (3 + 4) / 2.0 do not create an integer sum: all three literals become Doubles.

The flexibility belongs to literals only. Once a literal is stored in a constant, its type is fixed, and an Int constant never mixes with a Double constant without an explicit Double(…) (see the mistakes section and Swift arithmetic operators).

Five Places Swift Takes Type Clues From

Each example shows one source of clues. Real code usually combines several in one statement.

From an initializer, a function result or a property default

The simplest clue is the type of the value on the right of the =. When that value comes from a function, the function's declared return type is the clue.

Swift
func makeGreeting(for name: String) -> String {
    "Hello, \(name)!"
}

struct Settings {
    var volume = 0.5
    var retries = 3
}

let greeting = makeGreeting(for: "Ana")
let settings = Settings(volume: 0.8, retries: 5)
print(type(of: greeting), type(of: settings.volume), type(of: settings.retries))
// Output: String Double Int
Output✓ Tested · Swift 6.4
String Double Int

Stored properties with a default value are inferred too, and the memberwise initializer uses those types, so Settings(volume:retries:) takes a Double and an Int.

From the context: annotations, parameter types and overloads

Clues also travel from the outside in. An annotation, a parameter type or an expected return type tells the literals and overloaded calls inside an expression what to become. This is often called bidirectional type inference.

Swift
enum Speed { case slow, fast }

func setSpeed(_ speed: Speed) {
    print("Speed: \(speed)")
}

func defaultValue() -> Int { 10 }
func defaultValue() -> String { "ten" }

let ratio: Double = 3 / 8
let label: String = defaultValue()
setSpeed(.fast)
print(ratio, label)
// Output:
// Speed: fast
// 0.375 ten
Output✓ Tested · Swift 6.4
Speed: fast
0.375 ten

The annotation made 3 and 8 Doubles, so the division gives 0.375 instead of the integer result 0. The second annotation picked the String version of defaultValue(); without it the compiler reports ambiguous use of 'defaultValue()' (see Swift function overloading). And .fast was found inside Speed because setSpeed expects a Speed.

From the function a closure is passed to

A closure passed to map, sorted or filter rarely needs types, because the function's signature supplies them.

Swift
let words = ["kiwi", "banana", "fig"]

let lengths = words.map { $0.count }
let shortestFirst = words.sorted { $0.count < $1.count }
let labels = words.map { word in
    let upper = word.uppercased()
    return "\(upper) (\(word.count))"
}

print(lengths, shortestFirst)
print(labels)
// Output:
// [4, 6, 3] ["fig", "kiwi", "banana"]
// ["KIWI (4)", "BANANA (6)", "FIG (3)"]
Output✓ Tested · Swift 6.4
[4, 6, 3] ["fig", "kiwi", "banana"]
["KIWI (4)", "BANANA (6)", "FIG (3)"]

map runs on a [String], so $0 is a String. The closure returns an Int, so map's generic result becomes [Int]. The closure for labels has two statements and gets the same treatment: since Swift 5.7 the compiler infers types for multi-statement closures too.

A closure stored in a constant has no function around it to supply clues, so only its own body counts:

Swift
let double = { $0 * 2 }
let greet = { (name: String) in "Hi, \(name)" }
print(type(of: double))
print(type(of: greet))
// Output:
// (Int) -> Int
// (String) -> String
Output✓ Tested · Swift 6.4
(Int) -> Int
(String) -> String

double became (Int) -> Int: the literal 2 took its default type and $0 had to match it. With no clue at all, as in let same = { $0 }, the compiler stops with cannot infer type of closure parameter '$0' without a type annotation. The Swift closures article explains the shorthand syntax.

From the arguments of a generic function

A generic function has a placeholder type, usually T. The compiler picks T so that every argument fits.

Swift
func largest<T: Comparable>(_ a: T, _ b: T) -> T {
    a > b ? a : b
}

print(largest(3, 7.5))
print(largest("pear", "apple"))

let unique: Set = [3, 1, 3, 2]
print(type(of: unique), unique.count)
// Output:
// 7.5
// pear
// Set<Int> 3
Output✓ Tested · Swift 6.4
7.5
pear
Set<Int> 3

For largest(3, 7.5), the literal 3 can be a Double but 7.5 cannot be an Int, so T is Double. The Set annotation has no angle brackets: you can name a generic type and let Swift infer its Element. When no single type fits, as in largest(3, "a"), the error says so: conflicting arguments to generic parameter 'T' ('Int' vs. 'String').

When the placeholder appears only in the return type, the arguments give no clue, and you must supply the type:

Swift
func parse<T: LosslessStringConvertible>(_ text: String) -> T? {
    T(text)
}

let port: Int? = parse("8080")
let share = parse("0.25") as Double?
print(port ?? 0, share ?? 0)
// Output: 8080 0.25
Output✓ Tested · Swift 6.4
8080 0.25

let value = parse("8080") fails with generic parameter 'T' could not be inferred. This is why JSONDecoder's decode(_:from:) takes the type as an argument (User.self): it gives the compiler the clue a return type cannot. See Swift generics for writing your own generic code.

From the elements of a collection literal

For an array or dictionary literal, the compiler looks for one element type that fits every element.

Swift
let readings = [1, 2.5, 4]
let menu = ["tea": 3, "cake": 4.5]
let maybeScores = [90, nil, 75]
print(type(of: readings), readings)
print(type(of: menu))
print(type(of: maybeScores))
// Output:
// Array<Double> [1.0, 2.5, 4.0]
// Dictionary<String, Double>
// Array<Optional<Int>>
Output✓ Tested · Swift 6.4
Array<Double> [1.0, 2.5, 4.0]
Dictionary<String, Double>
Array<Optional<Int>>

One decimal makes every number a Double, and one nil makes the elements optional. Unrelated types fail: [1, "a"] gives heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional. Swift will not quietly create an [Any].

Where Swift Type Inference Stops

Most confusing inference errors come from one of these limits, and each one tells you where a written type is needed.

One statement at a time, never from later lines

The compiler decides a declaration's type before it reads the next line. var scores = [] fails at once with empty collection literal requires an explicit type, even if the next line appends an Int. var note = nil fails with 'nil' requires a contextual type. Give the clue on the declaration line:

Swift
var scores: [Int] = []
let nickname: String? = nil
var total = 0.0

scores.append(90)
total += 2.5
print(scores, nickname ?? "none", total)
// Output: [90] none 2.5
Output✓ Tested · Swift 6.4
[90] none 2.5

Writing 0.0 instead of 0 is enough to make total a Double. The Swift type annotation article lists every place an annotation like : [Int] can go.

Function signatures and computed properties are never inferred

Parameter types, return types and computed property types must be written. Swift infers inside a function body but not across its boundary, so each function's interface is visible in its declaration. Leaving out a return type does not mean "infer it"; it means "returns nothing". A computed property without a type fails with computed property must have an explicit type. Closures are the exception, because a closure is an expression inside a statement the compiler is already solving.

if and switch expressions check each branch separately

Since Swift 5.9 you can write let x = if … else …. Each branch of an if or switch expression is type-checked on its own, so a literal in one branch cannot see the other. The ternary operator is solved as one expression, so it can.

Swift
let useDecimal = true
let a = useDecimal ? 1 : 2.5
let b: Double = if useDecimal { 1 } else { 2.5 }
print(a, b)
// Output: 1.0 1.0
Output✓ Tested · Swift 6.4
1.0 1.0

Without the : Double, the if version fails with branches have mismatching types 'Int' and 'Double', because the first branch already settled on Int. The Swift ternary operator article compares the two forms.

Why Swift Says an Expression Is Too Complex to Type-Check

Swift operators are heavily overloaded: there are + functions for Int, Double, Float, String, arrays and more, and every literal can become several types. Each extra operator and literal multiplies the combinations the solver may have to try. The solver has a fixed budget, and when it runs out it reports the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions. The code can be perfectly valid.

Problem: Integer literals mixed with one decimal literal leave too many combinations of overloads and literal types, so the Swift 6.4 compiler gives up on this line even though every term is a plain number.

Swift
let score = 1 + 2 * 3 - 4 / 5 + 6 * 7 + 8.0
print(score)
// error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
Compiler output✓ Tested · Swift 6.4
error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

Fix: Tell the compiler the type of the result. One annotation removes most of the combinations, and the same line compiles at once:

Swift
let score: Double = 1 + 2 * 3 - 4 / 5 + 6 * 7 + 8.0
print(score)
// Output: 56.2
Output✓ Tested · Swift 6.4
56.2

The result is 56.2, not 57: with every literal a Double, 4 / 5 is 0.8 rather than 0. Writing the type also makes you decide which arithmetic you meant.

In real code the message often hides a genuine type error, because the solver runs out of time before it can report the real problem.

Problem: a, b and c are Int values and the end of the expression is a Double, which Swift does not allow, but the message does not say so.

Swift
let a = 1, b = 2, c = 3
let total = a + b * 2 - c / 3 + (a - b) * c + Double(a) / 2.0
// error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
Compiler output✓ Tested · Swift 6.4
error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

Fix: Split the expression into named steps. Each statement is small, so the compiler either succeeds or names the real problem. Split without a conversion (let total = integerPart + Double(a) / 2.0), this code reports the real problem, binary operator '+' cannot be applied to operands of type 'Int' and 'Double'; converting the integer part solves it:

Swift
let a = 1, b = 2, c = 3
let integerPart = a + b * 2 - c / 3 + (a - b) * c
let total = Double(integerPart) + Double(a) / 2.0
print(total)
// Output: 1.5
Output✓ Tested · Swift 6.4
1.5

Where the limit falls changes between compiler versions, so a long expression that compiles today may not stay fast as it grows.

Predict the Output

Both snippets test how far the clues of a single statement reach.

Snippet 1: literals and division

Swift
let a = 7 / 2 + 0.5
let b = 7 / 2
let c = Double(b) + 0.5
print(a, c)

What does this print?

Show answer

It prints 4.0 3.5.

On the first line no literal has a type until the whole statement is solved. 0.5 forces Double, so 7 and 2 become Doubles, 7 / 2 is 3.5, and a is 4.0. On the second line nothing asks for a Double, so the literals take the default Int and 7 / 2 is integer division: 3. Converting that 3 afterwards gives 3.0, plus 0.5 is 3.5.

Snippet 2: a closure stored in a constant

Swift
let double = { $0 * 2 }
print(double(21))
print(double(2.5))

What happens?

Show answer

The program does not compile. Line 3 fails with cannot convert value of type 'Double' to expected argument type 'Int'.

The type of double is decided on line 1, using line 1 alone. The literal 2 takes its default type Int, so the closure is (Int) -> Int, and Swift never changes it because of a later call. Without line 3, the program would print 42. To accept decimals, give the parameter a type:

Swift
let double = { (x: Double) in x * 2 }
print(double(21))
print(double(2.5))
// Output:
// 42.0
// 5.0
Output✓ Tested · Swift 6.4
42.0
5.0

Common Type Inference Mistakes and the Errors They Cause

Declaring an empty array and expecting the next line to set its type

An empty array literal has no elements to look at, and the compiler does not wait for the append on the next line.

Problem: The type of tags must be decided on its own line, and [] gives no element type, so Swift reports empty collection literal requires an explicit type.

Swift
var tags = []
tags.append("swift")
Compiler output✓ Tested · Swift 6.4
error: empty collection literal requires an explicit type

Fix: Put the element type on the declaration, with an annotation or with the initializer syntax [String]().

Swift
var tags: [String] = []
tags.append("swift")
print(tags)
// Output: ["swift"]
Output✓ Tested · Swift 6.4
["swift"]

The corrected version works because the annotation gives the clue the empty literal could not.

Starting a running total with an integer literal

var total = 0 looks neutral, but it makes total an Int for the rest of its life.

Problem: total is inferred as Int from the literal 0, so adding a Double price to it fails with cannot convert value of type 'Double' to expected argument type 'Int'.

Swift
let prices = [4.5, 12.25, 3.25]
var total = 0
for price in prices {
    total += price
}
Compiler output✓ Tested · Swift 6.4
error: cannot convert value of type 'Double' to expected argument type 'Int'

Fix: Start with a decimal literal, or annotate var total: Double = 0.

Swift
let prices = [4.5, 12.25, 3.25]
var total = 0.0
for price in prices {
    total += price
}
print(total)
// Output: 20.0
Output✓ Tested · Swift 6.4
20.0

The corrected version works because 0.0 is a floating-point literal, so total is a Double from the start.

Expecting an inferred Int to mix with a Double

After seeing 1 + 2.0 work, it is easy to expect the same from two constants.

Problem: quantity was inferred as Int on its own line, and there is no * that takes an Int and a Double, so Swift reports binary operator '*' cannot be applied to operands of type 'Int' and 'Double'.

Swift
let quantity = 3
let unitPrice = 2.5
let cost = quantity * unitPrice
Compiler output✓ Tested · Swift 6.4
error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'

Fix: Convert the Int explicitly where the two values meet.

Swift
let quantity = 3
let unitPrice = 2.5
let cost = Double(quantity) * unitPrice
print(cost)
// Output: 7.5
Output✓ Tested · Swift 6.4
7.5

The corrected version works because both operands are now Double values, which one * overload accepts.

Leaving out a function's return type

Inside a function body Swift infers freely, so it is natural to expect the same for the result.

Problem: A function without -> returns nothing (Void), so returning a number fails with unexpected non-void return value in void function.

Swift
func discount(for total: Double) {
    return total > 100 ? 10 : 0
}
Compiler output✓ Tested · Swift 6.4
error: unexpected non-void return value in void function

Fix: Write the return type. The literals in the body then become that type.

Swift
func discount(for total: Double) -> Double {
    total > 100 ? 10 : 0
}
print(discount(for: 150))
// Output: 10.0
Output✓ Tested · Swift 6.4
10.0

The corrected version works because the declared return type is the clue that makes 10 and 0 Doubles.

Find the Bug

This code should print the average rating, 4.5. It compiles and runs without warnings, but prints 4.0. Find the bug.

Swift
let ratings = [5, 4, 4, 5]
let total = ratings.reduce(0, +)
let average = Double(total / ratings.count)
print("Average rating: \(average)")
// Output: Average rating: 4.0
Show answer

total is an Int: reduce starts from the literal 0 and adds Int elements. ratings.count is an Int too. So total / ratings.count is integer division, 18 / 4 = 4, and it happens before Double(…) is called. The conversion only turns the truncated 4 into 4.0.

Wrapping literals does not help either: Double(18 / 4) is also 4.0. Double's initializer is overloaded for many argument types, so it does not push Double onto the expression inside it, and the literals take their default Int. Convert the operands, not the result:

Swift
let ratings = [5, 4, 4, 5]
let total = ratings.reduce(0, +)
let average = Double(total) / Double(ratings.count)
print("Average rating: \(average)")
// Output: Average rating: 4.5
Output✓ Tested · Swift 6.4
Average rating: 4.5

When to Rely on Inference and When to Write the Type

Inference is the normal Swift style for local values whose type is obvious from the right-hand side. Write the type when inference cannot decide, or would decide something other than what you mean.

Situation What inference gives What to write
An obvious value: let name = "Ana" The right type Nothing
An empty collection or nil An error var ids: [Int] = [], let note: String? = nil
A decimal value that starts as a whole number Int var total = 0.0
A value that must be Float, UInt8, Int64 or Character The default (Double, Int, String) let level: UInt8 = 200
A generic placeholder that appears only in the return type An error An annotation, or a type argument such as User.self
A long arithmetic expression A slow or failing type check Annotate the result or split it into steps

This article explains the mechanism. For the style question of when an explicit type makes code easier to read, for example in public APIs and code review, see Swift type inference vs explicit types. For the syntax of annotations on constants, parameters, tuples and closures, see Swift type annotation.

Try It Yourself

  • Create an empty array prices that will hold decimal prices, then append 4.5, 2.25 and 10 (write the last one as a whole number).
  • Store a quantity of 3 and let Swift infer its type.
  • Compute subtotal as the sum of prices with reduce(0, +), and total as subtotal times the quantity.
  • Write a function formatPrice(_:) that takes a Double and returns a String starting with $.
  • Print subtotal and total with their types, then the formatted total.

Expected output, on three lines: 16.75 Double, 50.25 Double and Total: $50.25.

Hint: once the array is [Double], the literal 10 and the 0 in reduce(0, +) become Doubles too. The quantity is an Int, so it needs a conversion.

Show solution
Swift
var prices: [Double] = []
prices.append(4.5)
prices.append(2.25)
prices.append(10)

let quantity = 3
let subtotal = prices.reduce(0, +)
let total = subtotal * Double(quantity)

func formatPrice(_ value: Double) -> String {
    "$\(value)"
}

print(subtotal, type(of: subtotal))
print(total, type(of: total))
print("Total: \(formatPrice(total))")
// Output:
// 16.75 Double
// 50.25 Double
// Total: $50.25
Output✓ Tested · Swift 6.4
16.75 Double
50.25 Double
Total: $50.25

Summary

  • Swift infers every type at compile time from clues: literals, operators, function signatures and annotations. An inferred type is as fixed as a written one.
  • Literals have default types (Int, Double, String, Bool, Array, Dictionary) but stay flexible until the statement is solved, so 1 + 2.0 is a Double while an Int constant and a Double constant never mix.
  • Clues flow both ways: an annotation or a parameter type decides literals, overloads and implicit members such as .fast.
  • Closures take their types from the function they are passed to; generic placeholders take theirs from the arguments, and need an annotation when they appear only in the return type.
  • Inference stops at the end of a statement and at function signatures: empty literals, nil, parameters and return types need a written type.
  • "Unable to type-check this expression in reasonable time" means too many combinations, not always wrong code: annotate the result or split the expression.

A good next step is Swift type annotation, which shows the syntax for giving the compiler each of these clues yourself.