Wrapped and Projected Value in Swift 5.2

Xinyi Xiang
2 min readSep 29, 2020

Property Wrappers

To understand what wrapped value and projected value are, we will have to first figure out the usages of property wrappers.

We saw the future of Swift, and it was full of @s.

— NSHipster in Swift Property Wrappers

You may see lots of @Something statements in Swift, these are what’s called property wrappers. Essentially, Property wrappers can be defined by using struct, class, or enum. The encapsulated behavior is further applied to the variables (or vars) wrapped, enabling code reuse and elegant programming scheme.

An example is @Published, this property wrapper allows a var to publish the changes we impose on it. In this specific case we have, the changes are periodically published and never fails, kind of like an ideal mapping tool, never failing to show updates and you see the traffics/construction after refreshing.

@Published var roadMap: RoadMap = RoadMap()
// essentially creates a struct
struct Published {
var wrappedValue: RoadMap
// creates (roughly) the below var _roadMap and set/get pair
var projectedValue: Publisher<RoadMap,Never>
}// roughly what Swift does for you
var _roadMap:Published = Published(wrappedValue: RoadMap())
//computed property
var roadMap: RoadMap {
get{_roadMap.wrappedValue}
set(_roadMap.wrappedValue = newValue }
// $roadMap to access the publisher
}

Accessing the values

In summary, if you don’t add anything in front of roadMap, you are accessing its computed values through set/get. If you use underscore in front, _roadMap is accessing the wrappedValue. And another syntactic sugar would be $roadMap to access the projectedValue, in this example, our projected value is a publisher that publishes any change it detects.

Reasons for using the property wrappers

It’s not hard to see that property wrappers give us the abilities to invoke actions on the set/get pairs. In our roadmap example above, we had changes publish through the projectValue (i.e. a publisher). More so with this implied, we can have more logics attach to the values. See this example of wrapping color intensities to an RGB type using @UnitInterval, the first example also demonstrates how you could use other property wrappers when implementing one.

Another important fact is that by wrapping, no values can be used after their expiration, enforcing the level of protection on our vars.

Further readings

3 Property Wrappers to Control Your Data in Swift | David Piper | https://medium.com/better-programming/3-property-wrappers-to-control-your-data-in-swift-84bcbb22c5be

The Swift Programming Language | Property Wrappers | https://docs.swift.org/swift-book/LanguageGuide/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID254

Implementing a Value Clamping Property Wrapper | NSHipster | https://nshipster.com/propertywrapper/#implementing-a-value-clamping-property-wrapper

--

--