KeyPath in Swift — Part 1

Ashish Yadav
2 min readJan 19, 2023

--

It is a very interesting topic and it can be use in many ways that we will discuss in the Article. Apple introduce it in version of Swift4. So let’s start about it without wasting a time.

KeyPath is a type because it represent the reference of properties and subscripts.

Therefore, keyPath is a type, we can store it in a variable, pass it around, even perform an operation on it.

KeyPath Expression

\Type Name. path

Type Name

Basically Type Name is name of a concrete type. Examples are:-

In the above example “String” is a type name.

Path

A path can be property, subscript, optional chaining expression and forced unwrapping expression.

Basically everything that we use reference value on instance of struct/object. Moreover, path can also refer computed property name.

Syntax of KeyPath

By replacing any class/struct instance with a backslash “\” and it followed by the instance type.

Moreover, Swift omitted the type name where it is inferred. So, keyPath can be defined without the Type Name.

The above article is about the basic of KeyPath like its definition, syntax and use. I hope, you guys get the idea of keyPath.

In the next article, we will discussed about the Type of KeyPath.

--

--