onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
675 stars 33 forks source link

How to map Binding with optional value in SwiftUI #838

Open onmyway133 opened 3 years ago

onmyway133 commented 3 years ago

We can write our custom Binding

import SwiftUI

extension Binding where Value == Date? {
    func flatten(defaultValue: Date) -> Binding<Date> {
        Binding<Date>(
            get: { wrappedValue ?? defaultValue },
            set: {
                wrappedValue = $0
            }
        )
    }
}

Then use in places where it needs Binding with non-optional value

DatePicker(
    "",
    selection: $date.flatten(defaultValue: Date()),
    displayedComponents: .hourAndMinute
)
.datePickerStyle(WheelDatePickerStyle())
basememara commented 3 years ago

This is great, thx for sharing! I used this to overload the nil coalescing operator:

public func ??<T>(optional: Binding<T?>, defaultValue: T) -> Binding<T> {
    Binding<T>(
        get: { optional.wrappedValue ?? defaultValue },
        set: { optional.wrappedValue = $0 }
    )
}

// Usage
DatePicker("Date", selection: $date ?? Date()))
onmyway133 commented 3 years ago

@basememara thanks for sharing, this is clever 👍