Property wrappers in Swift

Why need ????

Like we want to perform a task whenever initialize the property or change the property value. We have WillSet/DidSet to perform but it seems to repeated for every property. To avoid this property wrapper comes in existence.

Introduce in swift 5.1

There are two requirements for a property wrapper type [1]:

  1. It must be defined with the attribute @propertyWrapper.
  2. It must have a wrappedValue property, and wrappedValue is computed property.

Usage Restrictions

  • A property with a wrapper cannot be overridden in a subclass.
  • A property with a wrapper cannot be lazy, @NSCopying, @NSManaged, weak, or unowned.
  • A property with a wrapper cannot have custom set or get method.
  • wrappedValue, init(wrappedValue:) and projectedValue must have the same access control level as the wrapper type itself.
  • A property with a wrapper cannot be declared in a protocol or an extension.

To Avoid race condition we are using locks, likes: NSLock, os_unfair_lock, pthread_rwlock_t, DispatchSemaphore, serial DispatchQueue and OperationQueue.

Let's see how the wrapper class helps in race condition

Atomic Wrapper that helps for the serial data flow

How to use:

A wrapper that will help Capitalized initial character

How to use:

A wrapper class that will help you to save the model data

How to use:

An example of a wrapper class that will help you to save the data, like we save in the Userdefault

How to use:

GitHub Link: https://github.com/Nirajpaul2/PropertyWrapper

Important Links:
https://github.com/marksands/BetterCodable

https://github.com/SvenTiigi/ValidatedPropertyKit

--

--

No responses yet