Inside Swift's `func logKey<T>(_ key: T)`, why does the overloaded call `describeKey(key)` pick the generic overload even when the caller passes an `Int`?
answer
- resolved once, not per caller
- only the declared constraints count
- same result at -O
- more specific constraint wins
- protocol requirement for per-type behaviour
basics
~20 sSwift resolves the call once, when it type-checks the generic body, and it uses only T's declared constraints. With an unconstrained T, only describeKey<T>(_:) fits. The Int overload is never a candidate, whatever type the caller passes.
solid answer
~40 sOverload resolution is static. The body of `logKey<T>` is type-checked once against its signature, and inside it `T` is just a placeholder. The `describeKey(_ key: Int)` overload needs an `Int`, and `T` is not known to be one, so the compiler binds the call to `describeKey<T>(_:)`. That choice is part of the program's meaning. It does not change when the optimizer later specializes `logKey` for `Int`, so a `-O` build prints the same "some key" as a debug build. Adding a constraint changes which overloads fit. In `logHashableKey<T: Hashable>`, an overload `describeKey<T: Hashable>` wins over the unconstrained one because it is more specific. To get per-type behaviour at run time, make the operation a protocol requirement that each type implements, so the call goes through the type's conformance.
code
swift · 15 linesfunc describeKey<T>(_ key: T) -> String { "some key" }
func describeKey<T: Hashable>(_ key: T) -> String { "hashable key" }
func describeKey(_ key: Int) -> String { "Int key \(key)" }
func logKey<T>(_ key: T) -> String {
describeKey(key) // resolved once: T has no constraints here
}
func logHashableKey<T: Hashable>(_ key: T) -> String {
describeKey(key) // resolved once: T is known only to be Hashable
}
print(describeKey(42)) // Int key 42
print(logKey(42)) // some key
print(logHashableKey(42)) // hashable keygo deeper
Recall that Swift picks among overloads at compile time, using the types it can see where the call is written.
Explain that inside a generic body T carries only its declared constraints, so only overloads that accept such a T are candidates.
Diagnose the silent fallback: show the ranking among fitting overloads, prove that -O does not change it, and fix it with a protocol requirement, not a cast.
Coach teams to avoid overloading shared helpers on concrete types that generic layers will call, and to put customization behind protocol requirements.
## The behaviour Given three overloads: ```swift func describeKey<T>(_ key: T) -> String { "some key" } func describeKey<T: Hashable>(_ key: T) -> String { "hashable key" } func describeKey(_ key: Int) -> String { "Int key \(key)" } ``` a direct call `describeKey(42)` prints **"Int key 42"**. But a generic wrapper `func logKey<T>(_ key: T) -> String { describeKey(key) }` prints **"some key"** for `logKey(42)`. Many developers expect the wrapper to "see" the `Int` and forward to the `Int` overload. Swift does not work that way. ## Why: overloads are chosen when the body is type-checked - **The generic body is type-checked once**, against its own declaration. It is not re-checked for each caller. - Inside `logKey`, `key` has type `T`, and `T` carries **only the constraints written in the signature**. Here there are none. - The type checker collects the overloads that accept a `T`. The `Int` overload needs an argument known to be `Int`, so it is not a candidate. The `T: Hashable` overload needs a proof of `Hashable` that the body cannot supply. - Only `describeKey<T>(_:)` fits, so the call is **bound to it permanently**. When `logKey(42)` runs, it executes that binding. Swift does not run overload resolution again on the run-time type. This is also what lets a generic body compile without knowing its callers. The compiler must give every expression in it one meaning, using nothing but the signature. A library can ship `logKey`, clients in other modules can call it with types the library never saw, and the call inside means the same thing for all of them. ## Ranking among the candidates that fit When more than one overload fits, Swift prefers the **more specific** one. A non-generic overload that fits is generally ranked above a generic one, and a more-constrained generic above a less-constrained one. | Call written in | Visible candidates | Chosen | Prints | |---|---|---|---| | top level, `describeKey(42)` | all three | `describeKey(_: Int)` | Int key 42 | | `logKey<T>`, unconstrained | `describeKey<T>` | `describeKey<T>` | some key | | `logHashableKey<T: Hashable>` | `describeKey<T>`, `describeKey<T: Hashable>` | `describeKey<T: Hashable>` | hashable key | Even with `T: Hashable` the `Int` overload stays out of reach, because `Hashable` does not imply `Int`. ## Optimization does not change the choice A release build may **specialize** `logKey` for `Int` and generate a copy in which `T` is `Int`. That copy still calls the overload the type checker chose, because specialization preserves meaning. Built with `-O` or with `-Onone`, the example prints the same three lines. (Specialization as a performance tool is covered with compiler optimization.) Code that "works in release" because of a different overload would be a compiler bug, not a technique to rely on. ## Getting per-type behaviour When the label really should depend on the concrete type, move the decision to a place that varies by type: 1. **Make it a protocol requirement.** For example, `protocol KeyDescribing { var keyDescription: String { get } }`, implemented by `Int` in an extension, with `logKey<T: KeyDescribing>`. The call goes through the conformance, so each type's own implementation runs. It has to be a requirement declared in the protocol. A method added only in a protocol extension is dispatched statically, which is covered with protocol default implementations. 2. **Overload the outer function too.** Adding `func logKey(_ key: Int)` lets direct callers with an `Int` reach the `Int` path. Code that is itself generic over `T` still reaches only the generic `logKey`. 3. **Cast at run time as a last resort.** `if let n = key as? Int { ... }` works. But it hard-codes a list of types and moves the check from the compiler to run time. ## Where this bites in real code - Logging and debugging helpers that overload `describe(_:)` or `format(_:)` for a few concrete types and then call them from a generic wrapper. - Generic caches or serializers that overload a `store(_:)` for `Data` or `String` and silently fall back to the general path. - Tests that call an overload directly, see the specific behaviour, and miss that production calls go through a generic layer. - Reviewers should ask, for every overload set reached from generic code, which overloads the **declared** constraints actually make visible.
- Would changing the wrapper to `logKey<T: Hashable>` make it reach the `Int` overload for `Int` keys?No. With `T: Hashable`, the overloads that fit are the unconstrained one and the `T: Hashable` one. The `Int` overload still needs an argument known to be `Int`. The compiler picks `describeKey<T: Hashable>`, the more specific of the two, so every key type, `Int` included, gets "hashable key".
- How do you make the wrapper print a type-specific label for `Int` without giving up genericity?Turn the label into a protocol requirement, for example `protocol KeyDescribing { var keyDescription: String { get } }`. Have `Int` implement it in an extension and constrain the wrapper `T: KeyDescribing`. The call then goes through `Int`'s conformance at run time. An `as? Int` check also works, but it hard-codes the type list and is checked only at run time.
- Swift picks the most specific overload at run time from the argument's actual type.
- Release builds specialize logKey for Int and therefore call the Int overload.
- Constraining the wrapper to T: Hashable lets it reach the Int overload for Int keys.
- Once a generic overload exists, the Int overload is unreachable even from direct calls.
- Marking the wrapper @inlinable lets it see each caller's concrete type and pick the Int overload.