Skip to content
Tutorials Center
My learning

Topics

Lesson 111 of 146 ยท Advanced Swift

Dynamic Features

Learn Swift's dynamic features: callAsFunction, @dynamicMemberLookup, @dynamicCallable and Mirror reflection, with runnable examples, pitfalls and design advice.

Swift is a statically typed language: the compiler knows the type of every expression, and a typo in a property name is a compile error. That is a huge strength, but it makes some programs awkward to write. How do you model a JSON document whose keys you cannot know in advance? How do you build a small DSL where shell.git.commit("-m", "msg") reads like a command line? How do you write a generic debug printer that walks over any value?

Swift answers with a small set of dynamic features. They do not turn the language into Python or Ruby. Each one is a narrow hook that lets you decide, in ordinary typed Swift code, what an unusual syntax means. The compiler still checks everything it can. In this lesson you will learn four of them: callAsFunction, @dynamicMemberLookup, @dynamicCallable and the reflection type Mirror.

These features exist mainly for interoperability (calling Python or JavaScript objects from Swift, which is where @dynamicMemberLookup and @dynamicCallable came from) and for ergonomics in libraries. Most application code never needs them. Reach for them when they make a call site clearly nicer, and prefer ordinary methods otherwise.

callAsFunction: values you can call

Define a method named callAsFunction on a type and you can call its instances as if they were functions. This is not a dynamic feature in the strict sense, since everything is still checked at compile time, but it is the gentlest member of the family and the one you are most likely to use.

Swift Calling a value like a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

p(2) evaluates the polynomial 1 + 2*2 + 3*4 and prints 17.0; the second line prints [1.0, 6.0, 17.0]. The counter prints 1 2 3 because callAsFunction can be mutating, so a callable value can carry state. The validator prints ok must be positive. A callable struct is a lightweight alternative to a closure when the function needs configuration, state, several related methods or a name in stack traces. callAsFunction may be async, throws and generic, and it can have argument labels like any method.

There is one limitation that surprises people: the instance is not automatically a function value. You cannot pass p where a (Double) -> Double is expected:

Swift A callable value is not a function type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler answers with error: no exact matches in call to instance method 'map', which is not very helpful. The fix is to turn the call into an ordinary function value: write map { p($0) } or map(p.callAsFunction). Remember this rule: callAsFunction changes the call syntax, not the type of the value.

@dynamicMemberLookup: properties that are not declared

Mark a type with @dynamicMemberLookup and give it a subscript with the label dynamicMember. Now any member access that the compiler cannot find in the normal way is rewritten into a call of that subscript, with the member name passed as a string.

Swift Dynamic members from a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line prints dark en none. Nothing named theme is declared anywhere; the compiler turned settings.theme into settings[dynamicMember: "theme"]. Setting works too, because the subscript has a setter, so the second line prints light.

The cost is that the compiler can no longer catch typos. settings.thme compiles and quietly returns nil. Autocomplete does not know the names either. That is the trade you make, and the reason to use this feature only where the member names are truly open-ended. When a type has its own member with the same name, the real member always wins and the dynamic subscript is not consulted:

Swift Real members win over dynamic ones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see real dynamic subtitle. A type without the attribute has no such fallback; the same access is an ordinary error, error: value of type 'NoDyn' has no member 'foo'.

Key path members: type-safe forwarding

A second form of the subscript takes a key path instead of a string, and it is fully type checked. The compiler only accepts member names that exist on the wrapped type, and passes you a key path for them. This is how wrapper types forward the properties of the value they hold, without writing every property by hand. SwiftUI's Binding type uses exactly this trick to let you write $person.name.

Swift Forwarding properties with key paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is Ada 36 and then Person(name: "Ada", age: 37). wrapped.age += 1 works through the writable key path. Which key path type you accept controls what callers can do. With a plain KeyPath the access is read-only, and assigning through a var wrapper is a compile error:

Swift Read-only forwarding (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler reports error: cannot assign to property: 'config' is immutable, even though the variable is declared with var. Reading config.port on the line before is fine (it would print 8080); only the assignment is rejected. Key paths are explained in Key Paths.

You can combine both subscripts on one type, and the string form can return the type itself, which allows chains like doc.user.name. This makes a convenient way to dig into loosely structured data:

Swift A dynamic JSON value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The three lines are Ada, y and nil. A missing key does not crash: nothing gives .null, .null.deeper gives .null again, and string finally returns nil. For real applications you will usually prefer Codable with a proper model type (see Codable and Working with JSON). A dynamic wrapper like this earns its place for exploratory scripts, configuration files with unknown keys and test helpers.

@dynamicMemberLookup can also be applied to protocols, which makes every conforming type dynamic, and to classes. The subscript can be provided in a protocol extension:

Swift Dynamic lookup on a protocol and on a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see <title> and 15 nil. Because Node is a class, assigning through the dynamic subscript works on a let constant, exactly like with any other class property.

@dynamicCallable: calls with any arguments

@dynamicCallable lets you call a value with arbitrary arguments and, optionally, arbitrary argument labels. You implement dynamicallyCall(withArguments:) for unlabeled calls and dynamicallyCall(withKeywordArguments:) for labeled ones. The first takes any ExpressibleByArrayLiteral type, the second an ExpressibleByDictionaryLiteral type; KeyValuePairs is the usual choice, because it keeps the order and allows repeated labels.

Swift A dynamically callable type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

shell(1, 2, 3) calls the first method and prints 6. shell(a: 1, b: 2, a: 3) calls the second one, which prints a=1,b=2,a=3; the repeated label is fine. An empty call goes to the unlabeled form and sums nothing, so it prints 0. The argument types are still checked: the compiler knows from your signatures that only Int values are acceptable.

Swift Wrong argument types are still errors (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get two errors: cannot convert value of type 'String' to expected argument type 'Int' for the second call, and cannot call value of non-function type 'Plain' for the third. The attribute opens a door, but the types behind it stay strict.

The real power appears when you combine the two attributes. With @dynamicMemberLookup each member access extends a command, and with @dynamicCallable the final call produces the result. This is the trick behind Swift wrappers around Python and other scripting languages:

Swift A tiny command-line DSL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The two lines are git commit -m msg and git status. It reads beautifully and is completely unchecked, since git.cmmit compiles just as happily. Use it for domain-specific languages where the vocabulary really is open, such as shell wrappers, query builders and foreign-language bridges, and document the common names in a normal method for tooling to find.

Mirror: looking inside a value

The three features above change syntax. Mirror works at run time: it lets you inspect the stored properties of any value without knowing its type. Create one with Mirror(reflecting: value), and read these parts:

  • children: a collection of (label: String?, value: Any) pairs for the stored properties, in declaration order. Labels are nil for unlabeled things such as array elements, and .0, .1 for unlabeled tuple elements.
  • displayStyle: an optional enum telling you whether the value is a struct, class, enum, tuple, collection, dictionary, set or optional.
  • subjectType: the type being reflected.
  • superclassMirror: for classes, the mirror of the parent class.
Swift Reflecting on values with Mirror

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output starts with struct 2 Point and then the two children, x 1 and y 2. The Shape mirror shows name circle, sides 0 and secret 42: reflection ignores access control, so private properties are visible, and then class. The next lines print collection tuple and dictionary. Sub reports only its own property ["b"], and you walk to the parent through superclassMirror, which reports ["a"]. descendant("x") digs into the children by label and returns Any?, so the program prints 1, and 3 after casting y to Int and adding one.

Because children yields values of type Any, you recurse into nested values with another Mirror(reflecting:). A recursive property counter shows the idea in a few lines:

Swift Walking nested values recursively

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

countProperties(Outer()) prints 4: inner, its two fields a and b, and text. The table prints rows such as name | pen, price | 1.5 and tags | ["a", "b"], and shows parent| nil for the first item and parent| 7 for the second. Optionals are the one thing to special-case: an optional's mirror has either one child (the wrapped value) or none, so a naive "\(field)" would print Optional(7).

Customizing and hiding with CustomReflectable

A type can control what Mirror shows by conforming to CustomReflectable and returning its own mirror. This is the supported way to hide secrets from dump(_:) and from debugging tools, and also the way to make a type with computed state look like a regular struct:

Swift CustomReflectable hides a password

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

dump prints โ–ฟ binary.Account followed by - user: "ada" and - password: "***", and the second line is ["user=ada", "password=***"]. The prefix binary. is the name of the module that the site's runner compiles your program into; in a real project it is your module's name.

What Mirror is good and bad at

Mirror is a read-only view: you cannot set a property through it, and Swift has no run-time API to call a method by name. It is also slow compared with normal property access, because it works through type metadata and boxes every value in Any. Do not use it in hot loops. Good uses are:

  • debug output, logging and test failure messages (dump is built on it);
  • generic utilities such as "print any struct as a table" or a quick equality check in tests;
  • serializers and inspectors written once and reused for many types, when a macro or Codable is not an option.

If you control the types, prefer compile-time solutions: Codable for serialization, protocols for behavior, key paths for property access and macros for code generation.

Choosing the right tool

Need Feature Checked by compiler?
Call an instance like a function, with state or configuration callAsFunction Fully
Forward the properties of a wrapped value @dynamicMemberLookup with a key path Fully
Open-ended names (JSON, config, scripting bridges) @dynamicMemberLookup with a string Argument and result types only
Call with arbitrary arguments or labels @dynamicCallable Argument types only
Inspect an unknown value at run time Mirror No, run time

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a type need so that you can write value(3) on one of its instances?

    callAsFunction makes instances callable with function-call syntax. It is checked at compile time, and the instance still is not a function value.
  2. 2. A struct has a real property title and a @dynamicMemberLookup subscript. What does value.title do?

    Dynamic member lookup is a fallback. Declared members always take precedence.
  3. 3. What is the main benefit of the key path form subscript<M>(dynamicMember: KeyPath<Value, M>) over the string form?

    With a key path the compiler validates the member name against the wrapped type, so typos are compile errors and the result has the exact property type.
  4. 4. Which statement about Mirror is true?

    Mirror exposes stored properties in declaration order, including private ones. It is read-only and noticeably slower than normal property access.
  5. 5. What does @dynamicCallable require you to implement?

    The attribute is satisfied by one or both dynamicallyCall methods; the first handles unlabeled calls, the second handles calls with argument labels.

Summary

  • callAsFunction lets instances be called like functions; it can be mutating, async, throws and generic, but the instance is not a function value (use p.callAsFunction or a closure when you need one).
  • @dynamicMemberLookup rewrites unknown member access into subscript(dynamicMember:), with a string or a key path. Real members win; string-based access loses typo checking.
  • Key path forwarding is type safe and ideal for wrappers; KeyPath is read-only, WritableKeyPath allows assignment.
  • @dynamicCallable accepts arbitrary arguments and labels through dynamicallyCall methods, while argument types stay checked.
  • Combined, the two attributes enable open-ended DSLs and language bridges; use them sparingly and document the vocabulary.
  • Mirror is a read-only, slow, run-time view of stored properties that ignores access control; customize it with CustomReflectable.
  • Prefer compile-time tools (Codable, protocols, key paths, macros) whenever you control the types.

Next: Functional Techniques