In Swift, what must a @dynamicCallable type implement, and how does the compiler choose between its two dynamicallyCall methods?
answer
- calling an instance like a function
- array literal vs dictionary literal
- labels decide which method
- unlabeled arguments get an empty key
basics
~10 sA @dynamicCallable type implements dynamicallyCall(withArguments:), taking an ExpressibleByArrayLiteral parameter, or dynamicallyCall(withKeywordArguments:), taking an ExpressibleByDictionaryLiteral one with string-literal keys, or both. A call with any argument label uses the keyword method.
solid answer
~40 s`@dynamicCallable` lets you call an instance as if it were a function with any number of arguments. The type must provide an instance method `dynamicallyCall(withArguments:)` whose single parameter conforms to `ExpressibleByArrayLiteral`, such as `[String]`, or `dynamicallyCall(withKeywordArguments:)` whose parameter conforms to `ExpressibleByDictionaryLiteral` with a `Key` that is `ExpressibleByStringLiteral`, or both. A call that includes a keyword argument goes to the keyword method, and unlabeled arguments in it arrive with an empty-string key; every other call goes to `withArguments`. All arguments must convert to the one element type the method declares, and the return type is whatever the method returns. Prefer `KeyValuePairs` for keywords, because a `Dictionary` traps on duplicate labels.
code
swift · 24 lines@dynamicCallable
struct Command {
let name: String
func dynamicallyCall(withArguments args: [String]) -> String {
([name] + args).joined(separator: " ")
}
func dynamicallyCall(
withKeywordArguments args: KeyValuePairs<String, String>
) -> String {
let parts = args.map { label, value in
label.isEmpty ? value : "--\(label)=\(value)"
}
return ([name] + parts).joined(separator: " ")
}
}
let git = Command(name: "git")
print(git("status", "--short")) // git status --short
print(git("commit", message: "fix", all: "1")) // git commit --message=fix --all=1
print(git.dynamicallyCall(withArguments: ["log"]))
// git(1) // error: cannot convert value of type 'Int' to expected
// // argument type 'Array<String>.ArrayLiteralElement' (aka 'String')go deeper
Recall that the attribute lets you call an instance like a function, and that it needs a dynamicallyCall method.
Explain the two methods, their array-literal and dictionary-literal parameters, and how labels decide which one a call uses.
Spot the run-time trap of a Dictionary keyword parameter and explain the empty-string key for unlabeled arguments.
Limit dynamic calls to genuinely dynamic boundaries, and prefer callAsFunction where the call shape is known so the compiler keeps checking it.
## What the attribute does `@dynamicCallable` can be applied to a class, structure, enumeration or protocol. It makes an instance callable with ordinary call syntax, `value(a, b, c)` or `value(label: a, b)`, and the compiler rewrites each such call into a call of one of two methods the type declares. The feature exists since Swift 5.0 (SE-0216) and is mostly used for wrappers around dynamically typed values and for small command-style DSLs; for a fixed, typed parameter list, `callAsFunction` is the simpler tool. ## The two methods and their requirements The type must provide at least one of these, as **instance** methods: | Method | Parameter must conform to | Used for | |---|---|---| | `dynamicallyCall(withArguments:)` | `ExpressibleByArrayLiteral`, for example `[String]` or `[Int]` | calls without argument labels | | `dynamicallyCall(withKeywordArguments:)` | `ExpressibleByDictionaryLiteral` whose `Key` is `ExpressibleByStringLiteral`, for example `KeyValuePairs<String, String>` or `[String: Int]` | calls with at least one label | Rules that follow from this: - **The return type is free.** Each method may return any type, including `Void`. - **Arguments are homogeneous.** Every argument must convert to the parameter's element type. A `Command` whose method takes `[String]` rejects `git(1)` with `cannot convert value of type 'Int' to expected argument type 'Array<String>.ArrayLiteralElement' (aka 'String')`. - **Missing methods are a compile error.** A `@dynamicCallable` type with neither valid method is rejected with `'@dynamicCallable' requires 'BadCall' to have either a valid 'dynamicallyCall(withArguments:)' method or 'dynamicallyCall(withKeywordArguments:)' method`. - **Static methods do not count.** A `static func dynamicallyCall` does not make instances callable; calling one fails with `cannot call value of non-function type`. ## How the compiler picks a method 1. If the call has **any argument label**, it goes to `dynamicallyCall(withKeywordArguments:)`. If the type lacks that method, the call is a compile error saying the type cannot be applied with keyword arguments. 2. Otherwise it goes to `dynamicallyCall(withArguments:)` if the type has one. 3. If the type has only the keyword method, an unlabeled call still works and reaches it. Inside the keyword method, **unlabeled arguments arrive with an empty-string key**. `git("commit", message: "fix")` passes the pairs `("", "commit")` and `("message", "fix")`, in call order. ## What the compiler generates A dynamic call is sugar for a direct call, and the method can still be called directly: - `git("status", "--short")` becomes `git.dynamicallyCall(withArguments: ["status", "--short"])`. - `git("commit", message: "fix")` becomes `git.dynamicallyCall(withKeywordArguments: ["": "commit", "message": "fix"])`, the arguments forming a dictionary literal. - If a method is declared `throws` or `async`, the call needs `try` or `await` like any other call. Combined with string-based `@dynamicMemberLookup`, `object.sum(1, 2, 3)` works in two steps: the member lookup returns a value, and that value, if its type is `@dynamicCallable`, is then called. A dedicated member-call method, `dynamicallyCallMethod`, was only a future direction in the proposal: in Swift 6.4 a type that declares just that method is rejected for lacking both `dynamicallyCall` methods. ## KeyValuePairs versus Dictionary The keyword parameter type matters at run time: - **`KeyValuePairs`** keeps every pair in call order and allows duplicates, so `repeatLabels(a: 1, b: 2, a: 1)` and several unlabeled arguments are fine. - **`Dictionary`** is built from a dictionary literal, and a literal with a repeated key traps: two unlabeled arguments both use the key `""`, so a call such as `counter(1, 2, x: 3)` stops with `Fatal error: Dictionary literal contains duplicate keys`. It also loses the order of the arguments. For almost every use, `KeyValuePairs<String, Value>` is the right parameter type. ## Where it fits and where it does not - It suits **values from a dynamically typed source**, often together with string-based `@dynamicMemberLookup`, so that `object.method(arg)` reads naturally in Swift. - It suits **command builders** whose arguments are all one type, such as the `Command` example that turns `git("status", "--short")` into a command line. - It does not give per-argument types or argument-count checks: everything is one element type and any count is accepted. When the parameters are known, `callAsFunction` with a normal signature keeps full type checking. ## What to remember - One or both of `dynamicallyCall(withArguments:)` and `dynamicallyCall(withKeywordArguments:)`, as instance methods. - Any label selects the keyword method; unlabeled arguments in it have the key `""`. - Use `KeyValuePairs` for keywords; a `Dictionary` traps on repeated labels.
- When would you use callAsFunction instead of @dynamicCallable?Whenever the parameters are known. A `callAsFunction` method has an ordinary signature, so each argument has its own type, labels are checked and the arity is fixed. `@dynamicCallable` accepts any number of arguments of one element type, which only pays off when the call shape is truly dynamic.
- Can a @dynamicCallable call throw?Yes. If `dynamicallyCall(withArguments:)` or `dynamicallyCall(withKeywordArguments:)` is declared `throws`, a dynamic call to it must be marked with `try`, exactly like a direct call to the method.
- dynamicallyCall can take any parameter type as long as it is a collection.
- A call with labels uses withArguments and silently drops the labels.
- A Dictionary parameter is safe for keyword calls with repeated labels.
- @dynamicCallable lets each argument have its own type, like a normal signature.
- A static dynamicallyCall method makes the type itself callable.