KeyPath in Swift — Part 2
Hello Flocks, I hope you all are well. In the previous article we discussed about the the basics of Keypath which enlighten you about the KePath. Furthur in today’s article, we will discuss about it types.
KeyPath Types
Swift introduce the KeyPath in Five types and it is categories in two:-
- Read-only KeyPaths
- Writable KeyPaths( can Read and Write)
Read Only KeyPaths
- KeyPath
- ParialKeyPath
- AnyKeyPath
Writable KeyPaths
- WritableKeyPath
- ReferenceWritableKeyPath
1. KeyPath
A keypath which provide only read access to the propery. A root can be Value/Reference semantics.
A property or subscripts provide an access of read only (such as let or subscripts with only get), KeyPath is inferred.
2. ParialKeyPath
It is a type erased KeyPath that erased the value type parameter.
ParialKeyPath comes in the picture where we need KeyPath that doesn't require a Value type parameter. It’s signature is PartialKeyPath<Root>. It is very useful when we are passing the keyPath without defining its Value parameter. As per the below example, printUserInfo function has a PartialKeyPath argument which can print the data of a user and the data can be any type. Right now, user lastName and Address object are printing through function.
3. AnyKeyPath
It is completely type erased parameter. It doesn’t have a Key and Value parameter.
It is useful when we perform some implementation with different type of objects.
Writable KeyPaths
Writeable Keypaths provide an access of read-write to a property and they are formed for either mutable properties or mutable instances.
1. WritableKeyPath
A KeyPath which provide an access of read-write to a property with Value semantic(can be struct or enum). It means, it is inferred when Root is Value type.
2. ReferenceWritableKeyPath
A KeyPath which provide an access of read-write to a property with reference semantic(such as class). It means, it is inferred when Root is class type.
Hence, the above article have a detailed of keyPath types and it usage. I hope, all the readers get a better clarity on the KeyPath and its usage.
I will come up with more articles soon :).