Why does a Swift factory `func makeParser(format: String) -> some Parser` fail to compile when its branches return different parser types?
answer
- one hidden type per declaration
- inferred from the return statements
- matching underlying types
- enum wrapper or any Parser
basics
~20 sAn opaque return type stands for exactly one concrete type, which the compiler infers from the body. Returning JSONLinesParser on one path and CSVParser on another gives two underlying types, so Swift rejects the declaration.
solid answer
~40 s`some Parser` in a return position does not mean "any parser": it means one specific type that the implementation chooses and keeps hidden. The compiler infers that underlying type from the `return` statements and requires all of them to agree; otherwise it reports that the function declares an opaque return type whose return statements "do not have matching underlying types", with a note naming each type. That uniqueness is what makes the result a real static type: every call returns the same type, `==` works when the return type includes `Equatable`, and the value can fill a generic type argument. To fix it, return one type that covers both cases, such as an enum conforming to `Parser`, or change the return type to `any Parser` and accept the box.
code
swift · 17 linesprotocol Parser {
func parse(_ line: String) -> [String]
}
struct JSONLinesParser: Parser {
func parse(_ line: String) -> [String] { [line] }
}
struct CSVParser: Parser {
func parse(_ line: String) -> [String] { line.split(separator: ",").map(String.init) }
}
func makeParser(format: String) -> some Parser {
if format == "json" {
return JSONLinesParser()
} else {
return CSVParser()
}
}go deeper
Recall that a function returning some Parser must return one concrete parser type on every path, even though callers never see the name of that type.
Explain that the compiler infers the hidden type from the return statements and rejects mismatches, and name the enum-wrapper fix and the any Parser fix.
Show what uniqueness buys callers: a stable type identity, == through Equatable, and a result that conforms and can be a generic argument. Pick a fix by whether the set of parser types is closed or open.
Treat an opaque return as a promise about the protocol only. A public factory that may later need several result types should consider any from the start rather than be forced into a wrapper.
## What an opaque return type promises `func makeParser(format: String) -> some Parser` says: "this function returns one specific type that conforms to `Parser`, and I will not tell you which." The important word is **one**. The compiler infers that **underlying type** from the function body, records it, and holds callers to the protocol's interface while it keeps using the real type itself. An opaque return is the mirror image of a generic parameter: with a generic, the caller picks the type; with an opaque return, the implementation does. ## How the compiler infers the underlying type Swift's diagnostic documentation for opaque type inference sets out the rules: - The body must give the compiler something to infer from: a function needs a `return` that produces a value, and a property needs an initializer expression or a getter. - **Every `return` must produce the same underlying type.** If one branch returns `JSONLinesParser()` and another returns `CSVParser()`, there are two candidates and no single answer. - A recursive function needs at least one `return` that is not a recursive call, and it may not build an infinitely nested type, such as a wrapper that contains the function's own result. For the two-branch factory, the Swift 6.4 compiler prints: ```plaintext error: function declares an opaque return type 'some Parser', but the return statements in its body do not have matching underlying types note: return statement has underlying type 'JSONLinesParser' note: return statement has underlying type 'CSVParser' ``` Casting each value with `as Parser` or `as any Parser` does not help. Both returns then have the type `any Parser`, which does not conform to `Parser`, so the compiler reports that `any Parser` cannot conform to `Parser`. ## Why one type, and what callers get for it Uniqueness is what turns the opaque type into a real static type: 1. **Identity.** Every call of `makeParser(format:)` returns the same type, so results can share a variable, and `makeJSON() == makeJSON()` compiles when the declaration reads `-> some Parser & Equatable`. 2. **Conformance.** The result really conforms to `Parser`, so it can become a generic type argument, such as `Pipeline<P: Parser>`, or fill two parameters that must share one type. An `any Parser` value cannot do either. 3. **Freedom to change.** Callers cannot name the type, so a later version of the function can return a different conforming type without changing its declaration. Uniqueness is per declaration and per set of generic arguments. In `func wrap<P: Parser>(_ base: P) -> some Parser`, the underlying type may depend on `P`, so `wrap(JSONLinesParser())` and `wrap(CSVParser())` have different opaque types, and neither result can be assigned to a variable holding the other. ## Three ways to fix the factory | Fix | Declared return type | What you give up | |---|---|---| | Wrap both parsers in one enum or struct that conforms to `Parser` | `some Parser` | you write and maintain the wrapper | | Return the box | `any Parser` | type identity; calls go through the box | | Return a hand-written type eraser | the eraser's own type | a forwarding layer to write and keep current | - The **enum wrapper** keeps `some`: the enum is the single underlying type, and each case holds one real parser. It fits when the set of formats is closed and known to the module. - **`any Parser`** is the smallest change and fits an open set of formats, such as parsers registered by plug-ins at run time. - A **type eraser** fits when callers need a concrete type that itself conforms to `Parser`. ## What the caller still cannot do The caller of `makeParser(format:)` sees only `Parser`'s members, cannot write the concrete type's name in its own declarations, and cannot assign the result of a different opaque function to the same variable; the compiler reports the two `some Parser` types as distinct. A dynamic cast such as `as? StatementParser` still succeeds at run time, because the value really has that type, but code that relies on it is coupled to a detail the factory is free to change. Swift 6.4 also accepts `-> some Parser?` without parentheses, meaning an optional of one opaque type. The one-type rule then applies to the wrapped value: the function may return `nil` on some paths, but every non-`nil` value must still have the same underlying type.
- Can the hidden type behind `-> some Parser` depend on the function's generic parameters?Yes. In `func wrap<P: Parser>(_ base: P) -> some Parser` the underlying type may be `P` itself, so `wrap(JSONLinesParser())` and `wrap(CSVParser())` return different opaque types. Uniqueness holds per declaration and per set of generic arguments; for any one `P`, every path must still return the same type.
- Can a caller recover the concrete parser from a `some Parser` result with `as?`?Yes. `some` hides the type from the static type system, not from the run time, so `makeParser(format: "csv") as? StatementParser` succeeds when that is the underlying type. Code that does this ties itself to an implementation detail the factory may change, so it is a smell outside tests.
- A some Parser return lets each return statement choose its own conforming type.
- Casting each returned value with as Parser makes the branches match.
- Callers of a some-returning function can use members only the concrete type has.
- Two calls of the same non-generic some-returning function may return different types.
- Switching the return type to any Parser keeps every capability of some Parser.
Assumes Swift 6.4: the one-underlying-type rule has held since opaque result types arrived in Swift 5.1, and the some Parser? spelling without parentheses is new in 6.4.