Why does Swift report ambiguous use of 'parse' when two parse(_:) overloads differ only in return type, and how do you resolve it?
answer
- full name includes labels
- return type joins resolution
- context picks the overload
- annotate, cast or rename
- defaults can shadow silently
basics
~20 sSwift resolves overloads by labels, argument types and the expected return type. Two parse(_:) overloads differing only in return type both fit a call with no contextual type; a type annotation, an as coercion or a typed parameter resolves it.
solid answer
~50 sSwift identifies a function by its full name, base name plus labels, and resolves a call using the argument types **and the type the context expects back**. `parse(_:) -> Int` and `parse(_:) -> Double` are a legal overload pair, but `let value = parse("4")` gives the type checker no way to choose, so it reports `ambiguous use of 'parse'`. You resolve it by supplying the expected type: `let value: Int = parse("4")`, `parse("4") as Double`, or passing the call straight into a parameter of known type. Calling it as a bare statement is ambiguous too, even beside a `Void` overload. Overloads that differ by **label** — `fetch(id:)` and `fetch(name:)` — never collide, because the label is part of the name. Two declarations differing only in parameter names are an invalid redeclaration. When overloads proliferate, distinct labels or base names usually read better than return-type overloading.
code
swift · 13 linesfunc parse(_ text: String) -> Int { Int(text) ?? 0 }
func parse(_ text: String) -> Double { Double(text) ?? 0 }
func takesInt(_ value: Int) { print("Int:", value) }
let whole: Int = parse("4") // annotation selects the Int overload
let ratio = parse("2.5") as Double // coercion selects the Double overload
takesInt(parse("7")) // the parameter type selects Int
print(whole, ratio)
func fetch(id: Int) -> String { "by id" }
func fetch(name: String) -> String { "by name" }
print(fetch(id: 1), fetch(name: "a")) // labels make these distinctgo deeper
Know that functions can share a base name when labels or types differ, and that labels are part of a Swift function's name.
Explain how the expected type selects among return-type overloads and the three ways to supply it: annotation, as, or a typed parameter.
Diagnose ambiguity errors from the candidate notes, spot the silent default-argument shadowing case, and argue for distinct labels when overloads multiply.
Weigh return-type overloading in a shared API against the annotation burden it puts on every caller; distinct labels age better.
## How Swift chooses an overload Swift allows several functions to share a base name. To pick one at a call site, the type checker considers: - the **full name**: base name plus argument labels, such as `fetch(id:)` versus `fetch(name:)`; - the **argument types** at the call; - the **contextual type** the call's result must have — the annotated type of a constant, the parameter type it is passed to, or an `as` coercion. The third input is the one people forget: a return type participates in overload resolution, so two functions with identical parameters and different return types are a legal overload set. ## Why the ambiguity appears ```swift func parse(_ text: String) -> Int { Int(text) ?? 0 } func parse(_ text: String) -> Double { Double(text) ?? 0 } let value = parse("4") // error: ambiguous use of 'parse' ``` `let value` has no annotation, so both overloads produce a valid program: `value` could be `Int` or `Double`. Neither is ranked better, so the compiler stops with `ambiguous use of 'parse'` and lists each candidate in a note. The same happens when the call is a bare statement: with no use of the result, nothing selects a return type. A pair returning `Int` and `Void` is ambiguous in that position as well. ## Four ways to resolve it 1. **Annotate the receiving declaration:** `let value: Int = parse("4")`. 2. **Coerce with `as`:** `parse("4") as Double`. This is a compile-time type coercion, not a run-time cast. 3. **Let a parameter supply the context:** in `takesInt(parse("4"))`, the parameter type `Int` selects the `Int` overload. 4. **Rename instead of overloading:** `parseInt(_:)` and `parseDouble(_:)`, or a distinguishing label such as `parse(_:as:)` taking the metatype. This removes the ambiguity for every caller rather than asking each one to annotate. ## Overloading by label never collides Because labels are part of the full name, overloads that differ by label are always distinguishable: ```swift func fetch(id: Int) -> String { "by id" } func fetch(name: String) -> String { "by name" } fetch(id: 7) // unambiguous ``` Parameter *names* are not part of the full name. `func f(a x: Int)` and `func f(a y: Int)` both declare `f(a:)`, and the second is rejected as `invalid redeclaration of 'f(a:)'`. | Overloads differ by | Example | Call without extra context | |---|---|---| | Argument label | `fetch(id:)` / `fetch(name:)` | always resolves | | Parameter type | `log(_: Int)` / `log(_: String)` | resolves from the argument | | Return type only | `parse(_:) -> Int` / `-> Double` | ambiguous until context is given | | Parameter name only | `f(a x:)` / `f(a y:)` | not allowed: redeclaration | ## Literals pick an overload too When overloads differ by parameter type, the argument's type decides, and a literal brings its own preference. With `log(_: Int)` and `log(_: Double)` declared: - `log(5)` calls the `Int` overload, because an integer literal's default type is `Int`; - `log(5.0)` calls the `Double` overload, because a floating-point literal defaults to `Double`; - `log(d)` with `let d: Double = 2` calls the `Double` overload, because `d` already has a type. The last line is the trap in review: the literal `2` became a `Double` through the annotation, so the same digits can reach different overloads depending on where they were typed. ## The silent case: defaults Ambiguity is the loud failure. The quiet one comes from default values. Given ```swift func g(_ x: Int) { print("one") } func g(_ x: Int, y: Int = 0) { print("two") } g(1) ``` the call compiles without a diagnostic and runs the first overload, the one that does not need a default filled in. A developer who adds the defaulted variant expecting existing calls to use it will find they do not. In review, treat an overload that differs from another only by trailing defaulted parameters as a smell: either merge them into one function with a default, or give them distinct labels. ## Practical guidance - Overloading by return type is legitimate, but it shifts work onto callers, who must supply a type. - Distinct labels state the difference at the call site, which is usually what readers need. - When an ambiguity error appears after adding an overload, read the candidate notes: they list every declaration the compiler considered. - Generic functions add another layer to resolution; that belongs with Swift's generics rather than here.
- In Swift, given g(_ x: Int) and g(_ x: Int, y: Int = 0), which one does g(1) call?The first. The call compiles without a warning, and Swift picks the overload that needs no default value filled in. That makes the defaulted overload unreachable without writing `y:`, which is a common surprise when someone adds a defaulted variant expecting existing calls to use it.
- Why might a library prefer parse(_:as:) taking a metatype over overloading parse(_:) by return type?With `parse("4", as: Int.self)` the caller states the type in the call itself, so it works in any position, including a bare statement or an untyped `let`. Return-type overloads only resolve when the surrounding code already supplies the type, which forces annotations on callers.
- Swift cannot overload two functions that differ only in return type
- Changing a parameter's internal name creates a valid overload
- An as coercion performs a run-time cast that may fail
- Swift always prefers the overload declared last in the file
- Adding a defaulted overload makes existing calls switch to it