In Swift, how does type inference choose a type for a literal, and when must you write a type annotation instead?
answer
- literals have no type alone
- context first, then a fallback
- Int, Double, String, Bool
- nil and [] have nothing to infer
basics
~20 sA Swift literal has no type of its own: the compiler takes one from context, such as an annotation or the other operands, else defaults to Int, Double, String or Bool. Annotate when that default is wrong or nothing can be inferred.
solid answer
~40 sSwift parses `3` or `4.5` as an untyped literal and lets type inference pick a type from the surrounding context. With no context it uses the default literal types: `Int` for integers, `Double` (never `Float`) for floating-point, `String` for text, `Bool` for `true`/`false`. That is why `let total = 3 * 4.5` compiles as a `Double`, while `quantity * unitPrice` with `let quantity = 3` and `let unitPrice = 4.5` fails: both constants already have types, `Int` and `Double`, and Swift never converts between them implicitly. You write an annotation when the default is wrong (`let discount: Float = 0.1`, `let maxItems: Int8 = 120`) or when there is nothing to infer from: `let notes = []` and `let coupon = nil` do not compile without a type.
code
swift · 9 lineslet quantity = 3 // Int
let unitPrice = 4.5 // Double
let total = 3 * 4.5 // Double: both literals adopt Double
let discount: Float = 0.1 // the annotation makes the literal a Float
let maxItems: Int8 = 120 // the annotation makes the literal an Int8
let notes: [String] = [] // an empty literal needs the annotation
// let lineTotal = quantity * unitPrice // error: Int and Double don't mix
let lineTotal = Double(quantity) * unitPrice
print(type(of: total), lineTotal, discount, maxItems, notes)go deeper
Name the default literal types, Int, Double, String and Bool, and give examples where an annotation is required, such as an empty array or nil.
Explain that literals stay untyped until inference resolves them, which is why 3 * 4.5 compiles while an Int constant times a Double constant does not.
Show how an annotation changes what the compiler can check, such as rejecting an overflowing literal at compile time, and when leaving types inferred keeps code clearer.
Discuss where a team wants annotations for readability, at API boundaries and on non-default numeric types, versus where inference is idiomatic and annotations only add noise.
## Literals are untyped until inference decides A **literal** is a value written directly in source: `42`, `4.5`, `"Ada"`, `true`, `[1, 2]`, `nil`. In Swift a literal **does not have a type on its own**. The compiler reads it with unlimited precision and asks type inference which type it should become. That type must be able to be created from that kind of literal, which the standard library expresses with protocols such as `ExpressibleByIntegerLiteral` and `ExpressibleByFloatLiteral`. **Type inference** works from context: - an explicit **type annotation** on the declaration (`let maxItems: Int8 = 120`); - the **other operands** of an expression (`3 * 4.5` makes both literals `Double`); - the **parameter type** of the function the literal is passed to; - the **element type** already established in a collection literal (`[1, 2.5]` becomes `[Double]`). ## The default literal types When nothing in the context decides, Swift falls back to a fixed default for each kind of literal: | Literal | Default type | Protocol a custom type adopts | |---|---|---| | `42`, `0xFF`, `1_000` | `Int` | `ExpressibleByIntegerLiteral` | | `4.5`, `1e3` | `Double` | `ExpressibleByFloatLiteral` | | `"Ada"` | `String` | `ExpressibleByStringLiteral` | | `true`, `false` | `Bool` | `ExpressibleByBooleanLiteral` | Two details matter in interviews. First, Swift **always picks `Double`, not `Float`**, for an unannotated floating-point literal; `Float` must be asked for. Second, the literal's *form* does not change the default: `0xFF` and `1_000_000` are still `Int`, and `1e3` is a `Double`. ## Why mixing works for literals but not for constants The classic confusion in a checkout calculation: 1. `let total = 3 * 4.5` compiles. Neither literal has a type yet, so inference finds one type that fits both, `Double`, and `total` is `13.5`. 2. `let quantity = 3` and `let unitPrice = 4.5` are separate declarations, so each literal was resolved on its own line: `quantity` is `Int`, `unitPrice` is `Double`. 3. `quantity * unitPrice` then fails with `binary operator '*' cannot be applied to operands of type 'Int' and 'Double'`. Swift performs **no implicit numeric conversion** between named values; you write `Double(quantity) * unitPrice`. The conversion rules themselves are covered with numbers. ## When an annotation is required or wise An annotation is a colon and a type after the name: `let discount: Float = 0.1`. Write one when: - **The default is wrong**: you need a `Float`, an `Int8`, a `UInt`, or a `Character` instead of a `String` for `"a"`. - **There is nothing to infer from**: `let notes = []` fails with `empty collection literal requires an explicit type`, and `let coupon = nil` fails with `'nil' requires a contextual type`. Write `let notes: [String] = []` and `let coupon: String? = nil`. - **The value arrives later**: a constant declared without a value (`let fee: Double`) has no literal to infer from. - **The literal does not fit**: an annotation also puts the compiler on guard, so `let small: Int8 = 300` is rejected at compile time with `integer literal '300' overflows when stored into 'Int8'`. Otherwise idiomatic Swift leaves the type out. `let orderID = "A-1042"` is as strongly typed as `let orderID: String = "A-1042"`; inference happens at compile time and the result is identical. Several declarations can share one line, each inferred separately: `var x = 0.0, y = 0.0`. ## Traps that look like inference bugs Most surprises come from a literal meeting a value whose type is already fixed: - **A typed constant meets a float literal**: with `let price = 5`, the expression `price * 1.1` fails with the same `Int` and `Double` error, because `1.1` cannot become an `Int` and `price` will not become a `Double`. - **A one-character string is still a `String`**: `let separator = "|"` is a `String`; you get a `Character` only with `let separator: Character = "|"` or where a `Character` parameter supplies the context. - **Inference is local to the declaration**: each `let` is resolved on its own line from its own initializer, never from how the constant is used further down the function. The cure in each case is the same: give the literal its context (an annotation or a typed operand) or convert the typed value explicitly. ## Summary for the whiteboard - Literals are untyped; context decides; defaults are `Int`, `Double`, `String`, `Bool`. - Named constants have fixed types, and Swift never converts between numeric types silently. - Annotate to choose a non-default type, to give `nil` or `[]` a type, or to declare now and assign later.
- In Swift, what type does the array literal [1, 2.5] get, and why?`[Double]`. The element literals are untyped, so inference looks for one element type that both `1` and `2.5` can become. `Int` cannot represent `2.5`, while `Double` can be created from an integer literal, so both elements become `Double`. Writing `let items: [Int] = [1, 2.5]` would fail instead, because `2.5` cannot become an `Int`.
- What happens in Swift with let small: Int8 = 300?It fails at compile time with `integer literal '300' overflows when stored into 'Int8'`. The annotation makes the literal an `Int8`, whose range ends at 127, and because the value is a literal the compiler can check it before the program runs. The same value computed at run time would follow the overflow rules for arithmetic instead.
- Does adding a type annotation change how a Swift value behaves at run time?Not when it names the type inference would have chosen anyway: `let orderID: String = "A-1042"` and `let orderID = "A-1042"` produce the same `String`. An annotation changes the result only when it changes the chosen type, such as `Float` instead of `Double`, or gives a type where inference has none, such as an empty array.
- Saying the literal 3 is an Int, so 3 * 4.5 cannot compile
- Claiming Swift infers Float for 2.5 because it is smaller
- Expecting let coupon = nil to produce an optional of some type
- Believing Swift silently converts an Int constant to Double in arithmetic
- Thinking an unannotated declaration is dynamically typed