In Swift, why does `quantity * unitPrice` fail to compile when quantity is an Int and unitPrice a Double, while `3 * 19.99` compiles?
answer
- values never change type silently
- literals have no type yet
- an initializer, not a cast
- Int(_:) drops the fraction
- Bool is not a number
basics
~20 sSwift never converts one numeric type to another implicitly, so Int * Double has no matching operator. Literals stay untyped until context picks a type, so 3 becomes a Double in 3 * 19.99. Convert variables explicitly: Double(quantity) * unitPrice.
solid answer
~40 sSwift has no implicit numeric conversion: `Int`, `Double` and every sized integer are distinct types, and `*` is declared for two operands of the same type, so `quantity * unitPrice` is rejected with "binary operator '*' cannot be applied to operands of type 'Int' and 'Double'". A literal is different: `3` has no type until context decides, so in `3 * 19.99` it becomes a `Double`. The fix is an initializer on the destination type, `Double(quantity) * unitPrice`; `quantity as Double` is a coercion and fails. Going back, `Int(_:)` rounds toward zero, so round first when you need the nearest whole number. The same rule keeps `Bool` apart: `if retries` with an `Int` does not compile; write `retries != 0`.
code
swift · 17 lineslet quantity = 3 // Int
let unitPrice = 19.99 // Double, never Float, for an unannotated literal
// let total = quantity * unitPrice
// error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
let total = Double(quantity) * unitPrice
let literalTotal = 3 * 19.99 // fine: the literal 3 becomes a Double
let wholeUnits = Int(total) // 59: Int(_:) rounds toward zero
print(total, literalTotal, wholeUnits) // 59.97 59.97 59
// if quantity { } // error: type 'Int' cannot be used as a boolean; test for '!= 0' instead
if quantity != 0 {
print("cart has items")
}
let small: UInt8 = 200
let wide: UInt16 = 2_000
print(wide + UInt16(small)) // 2200: widths are converted explicitly toogo deeper
Remember that Int and Double never mix without an explicit initializer such as Double(count), and that an Int cannot be an if condition.
Explain why literals adapt to context while variables do not, why as is a coercion rather than a conversion, and that Int(_:) truncates toward zero.
Choose where conversions happen, at data boundaries, and which rounding each one applies, so a price or a byte count never loses its fraction by accident.
Weigh the readability cost of explicit conversions against the class of silent precision bugs they remove when setting a team's numeric-type conventions.
## The rule: values never convert themselves Swift is **type-safe** in a strict sense: a value of one type is never implicitly converted to another. `Int`, `Double`, `Float`, `Int8`, `UInt16` and the rest are separate types, and the arithmetic operators are declared for two operands of the **same** type. So with - `let quantity = 3` inferred as `Int`, and - `let unitPrice = 19.99` inferred as `Double`, the expression `quantity * unitPrice` has no matching operator and the compiler reports "binary operator '*' cannot be applied to operands of type 'Int' and 'Double'". The same rule applies between integer widths: a `UInt16` and a `UInt8` cannot be added until one becomes the other's type. The point is to make every change of range or precision visible in the source, because each numeric type stores a different range of values. ## Literals are the exception A **numeric literal** such as `3` or `19.99` has no type of its own until the compiler picks one from context. Without context, an integer literal becomes `Int` and a floating-point literal becomes `Double`; Swift never infers `Float` for an unannotated literal. In `3 * 19.99` nothing forces the `3` to be an `Int`, so it becomes a `Double` and the expression compiles. The same flexibility explains `let total = 3 + 0.14159` (a `Double`) and `3 as Double` (legal: the literal is created as a `Double`). Variables do not get that flexibility. `quantity as Double` fails with "cannot convert value of type 'Int' to type 'Double' in coercion": `as` changes how a literal or an expression is typed, it does not convert a value that already has a type. Literals are also range-checked at compile time: - `let tooBig: Int8 = 128` fails with "integer literal '128' overflows when stored into 'Int8'"; - `let negative: UInt8 = -1` fails with "negative integer '-1' overflows when stored into unsigned type 'UInt8'"; - a literal used where a type is already known, such as `price * 2`, simply takes that type, so no conversion is needed for constants written inline. That last point is why code full of literals rarely meets the rule, and code full of variables meets it constantly. ## Converting explicitly Every conversion is an **initializer call** on the destination type: | From | To | Spelling | What happens | |---|---|---|---| | `Int` | `Double` | `Double(quantity)` | Exact for everyday values; very large integers round to the nearest `Double` | | `Double` | `Int` | `Int(total)` | Rounds **toward zero**: `4.75` becomes `4`, `-3.9` becomes `-3` | | `UInt8` | `UInt16` | `UInt16(small)` | Always fits, so it is exact | | `Int` | `Int8` | `Int8(value)` | Traps at run time if the value does not fit | So the fix is `Double(quantity) * unitPrice`, which produces a `Double`. If the result must be a whole number, decide how to round **before** converting: `Int(total)` truncates, while `Int(total.rounded())` rounds to the nearest. Converting the other way, `Int(unitPrice) * quantity`, compiles too but silently drops the cents, which is rarely what a price calculation wants. ## Bool is its own type The same rule keeps `Bool` separate from the numbers: - `if retries { … }` with an `Int` fails with "type 'Int' cannot be used as a boolean; test for '!= 0' instead"; - there is no `Bool(_:)` initializer that takes an `Int`, and no `Int(_:)` that takes a `Bool`, in the standard library; - write the comparison you mean: `if retries != 0`, or `retries > 0`. `Bool` has exactly two values, `true` and `false`, which unannotated `true` and `false` literals infer to. Mutating helpers such as `toggle()` exist, but arithmetic does not. ## Habits that keep conversions honest 1. Use `Int` for whole numbers and `Double` for fractions unless an external format dictates a sized type, so most expressions never need a conversion. 2. Convert at the **boundary** where data enters or leaves, not in the middle of every expression. 3. Choose the conversion that matches your intent: plain `Int(_:)` truncates; rounding, failable and saturating conversions are separate initializers. 4. Treat a cast-looking `as` on a numeric variable as a bug: it is a coercion, not a conversion. A team that follows these habits sees conversion errors as early, readable compile errors rather than wrong numbers at run time.
- Why does `let q = 3; let y = q as Double` fail while `let z = 3 as Double` compiles?`as` here is a coercion: it tells the type checker which type an expression should have. A literal can still become a `Double`, so `3 as Double` works. `q` is already an `Int`, and `as` never converts a value, so the compiler reports "cannot convert value of type 'Int' to type 'Double' in coercion". Use `Double(q)`.
- What does `Int(-3.9)` return in Swift, and how do you get -4 instead?It returns `-3`: converting a floating-point value with `Int(_:)` rounds toward zero before the range check. For the floor, round first with `(-3.9).rounded(.down)` and then convert; for the nearest whole number use `rounded()`, whose default rule is `.toNearestOrAwayFromZero`.
- Swift widens an Int to a Double automatically when the two meet in arithmetic.
- Writing quantity as Double converts the value, like a C cast.
- Int(2.7) rounds to the nearest whole number, 3.
- An integer literal like 3 is always an Int, wherever it appears.
- Any non-zero Int can be used directly as an if condition.