SwiftQuiz
#18

Dynamic Member Lookup Priority

  • dynamic-member-lookup
  • generics
Swift 6.3.2 Report an issue

Verified quizzes have their expected answer checked by compiling and running the code with the listed Swift toolchain during the site build.

@dynamicMemberLookup
struct Wrap<T> {
    var inner: T
    var y = 0
    subscript<U>(dynamicMember kp: KeyPath<T, U>) -> U {
        inner[keyPath: kp]
    }

    subscript(dynamicMember key: String) -> String {
        "\(key)"
    }
}

struct Inner {
    var x = 1
    var y = 2
}

let w = Wrap(inner: Inner())
print(w.x)
print(w.y)
print(w.z)
Hint

Three layers compete: a real stored property on Wrap (y), a key-path subscript over Inner, and a string subscript. What's the precedence?

Your answer

What does this program do?