How to get Binding via dollar prefix in SwiftUI

Khoa Pham
Khoa Pham
Nov 6, 2019 · 2 min read

The dollar is not a prefix, it seems to be a generated code for property wrapper, and each kind of property wrapper can determine which value it return via this dollar sign

State and ObservedObject are popular property wrappers in SwiftUI

State

Read State

A persistent value of a given type, through which a view reads and monitors the value.

If we have a simple State, we can access its 3 forms

@State private var image: UIImage

and here is what

image // UIImage
_image // State<UIImage>
$image // Binding<UIImage>

Also, with State, we can access Binding via projectedValue

_image.projectedValue // Binding<UIImage>

ObservableObject

Read ObservedObject

For a simple ObservableObject, we can see its 3 forms

class ViewModel: ObservableObject {
var objectWillChange = ObservableObjectPublisher()
var image: UIImage? {
didSet {
objectWillChange.send()
}
}
@ObservedObject var viewModel: ViewModel = ViewModel()viewModel // ViewModel
_viewModel // ObservedObject<ViewModel>
$viewModel // ObservedObject<ViewModel>.Wrapper

If we view the source code of ObservableObject, we can see its Wrapper which uses dynamicMemberLookup to provide Binding

@propertyWrapper public struct ObservedObject<ObjectType> : DynamicProperty where ObjectType : ObservableObject {    /// A wrapper of the underlying `ObservableObject` that can create
/// `Binding`s to its properties using dynamic member lookup.
@dynamicMemberLookup public struct Wrapper {
/// Creates a `Binding` to a value semantic property of a
/// reference type.
///
/// If `Value` is not value semantic, the updating behavior for
/// any views that make use of the resulting `Binding` is
/// unspecified.
public subscript<Subject>(dynamicMember keyPath: ReferenceWritableKeyPath<ObjectType, Subject>) -> Binding<Subject> { get }
}
public init(initialValue: ObjectType) public init(wrappedValue: ObjectType) public var wrappedValue: ObjectType public var projectedValue: ObservedObject<ObjectType>.Wrapper { get }
}

Conclusion

So now we know how to get Binding from State and ObservableObject, and the mysterious dollar sign. These are both convenient but confusing at first, but if we use it more, it will make more sense and hopefully we can learn to do the same for our own property wrappers

Fantageek

Simple apps that make sense

Khoa Pham

Written by

Khoa Pham

My apps https://onmyway133.github.io/

Fantageek

Fantageek

Simple apps that make sense

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade